比较字符串类型的字典键与C#中的另一个字符串

时间:2015-05-18 07:37:01

标签: c# dictionary

我实际上是在尝试检查string是否等于Dictionary对象中的任何一个键。

这是我到目前为止所做的:

using (var oStreamReader = new StreamReader(path))
{
    Dictionary<String, String> typeNames = new Dictionary<string, string>();
    typeNames.Add("Kind","nvarchar(1000)");
    typeNames.Add("Name","nvarchar(1000)");
    DataTable oDataTable = new DataTable();

    var headLine = oStreamReader.ReadLine().Trim().Replace("\"", ""); 
    var columnNames = headLine.Split(new[] { ';' });

    String[] oStreamDataValues;

    /*
    *create DataTable header with specific datatypes and names
    */

    int countCol = 0;

    foreach (string readColumn in columnNames)
    {


        if ((readColumn.ToString().Replace("\"", "").CompareTo(typeNames) == true))
        {
            // this comparison doesn't work
        }
    }
}

4 个答案:

答案 0 :(得分:4)

我不太清楚你到底想要达到的目标。如果您有C#dictonary,则可以使用linq检查与所需值匹配的值,例如

string valueToCompare = "Value to match";
Dictionary<string, string> dict = new Dictionary<string, string> 
                                  {
                                    {"Key 1", "A value"}, 
                                    {"Key 2", "Another value"}
                                  };
bool found= dict.Values
                .Any(value 
                     => 
                     value.Equals(valueToCompare,
                                  StringComparison.CurrentCultureIgnoreCase)
                    );

答案 1 :(得分:3)

由于您要检查词典中是否存在与columnNames对象中某个值相同的键,我建议您使用ContainsKey方法

答案 2 :(得分:0)

Dictionary<string, string> d = new Dictionary<string, string>();
            string keyvalue;
            if (d.ContainsKey("value to find"))
            {
                if (d.TryGetValue("value to find", out keyvalue))
                {
                    //// here keyvalue variable has the value 
                }
                else
                {
                    ///value is null or throws exception
                }
            }
            else
            {
                    ////key no exists
            }

答案 3 :(得分:0)

我已经解决了这个问题(Paul Houlston和Thomas Lielacher的灵感来源)

String headLine = oStreamReader.ReadLine().Trim().Replace("\"", ""); 
String columnNames = headLine.Split(new[] { ';' });



foreach (string readColumn in columnNames)  {

if (typeNames.Keys.Contains(readColumn, StringComparer.CurrentCultureIgnoreCase)==true)
    {
      DataColumn oDataColumn = new DataColumn(readColumn,typeof(System.String));
      oDataTable.Columns.Add(oDataColumn);
    }