我有一个字典,键为整数类型,值为字符串类型
I have a dictionary with key as integer type and value as string type
键-值
1-"A"
2-"B"
3-"c"
4-"D"
5-"E"
我有一个字符串类型的数组
and i have a array of string type
{"A","D","E"}
{"A","D","E"}
现在我想匹配字典和数组以使用字典键产生以下输出
Now i want to match dictionary and array to produce the below output with dictionary key
1:true 4:true 5:true
1:true 4:true 5:true
在上面的输出整数中表示字典关键字,其值"A"与数组匹配,即:-1 = true
In the above output integer indicates dictionary key saying value "A" is matched in array ie:- 1=true
推荐答案我将使用join查找匹配项:
Dictionary<int, string> dict = new Dictionary<int, string> { {1, "A"}, {2, "B"}, {3, "c"}, {4, "D"}, {5, "E"}, }; string[] values = new [] {"A","D","E"}; var query = from kvp in dict join s in values on kvp.Value equals s select new {kvp.Key, Found = true};您也可以使用where values.Contains(kvp.Value)代替联接,但是每次都会搜索数组,而联接将创建查找,查找效率更高.对于您发布的数据大小,可能不会有多少性能提升,但是对于大型馆藏,它可能会明显更快.
You could also use where values.Contains(kvp.Value) instead of a join, but that will search the array each time, while the join will create lookups which will be searched more efficiently. For the size of the data you posted, there probably isn't much performance gain, but for large collections it could be significantly faster.
更多推荐
使用Linq在c#中使用字典数组
发布评论