使用Linq在c#中使用字典数组

编程入门 行业动态 更新时间:2024-10-24 04:35:38
本文介绍了使用Linq在c#中使用字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字典,键为整数类型,值为字符串类型

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#中使用字典数组

本文发布于:2023-11-26 03:10:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字典   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!