我实际上是在尝试检查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
}
}
}
答案 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);
}