比较c#中string类型的Dictionary Key和另一个字符串
本文关键字:Key 另一个 字符串 Dictionary string 类型 比较 | 更新日期: 2023-09-27 17:49:35
我实际上是在检查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
}
}
}
我不太清楚你到底想达到什么目的。如果你有一个c#字典,你可以使用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)
);
既然你想检查你的字典中是否存在一个条目,作为你的columnNames
对象中一个值的相同键,我建议你使用ContainsKey方法
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
}
我已经解决了这个问题(受到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);
}
}