使用Linq在c#中使用字典数组 [英] Array with Dictionary in c# using Linq

查看:512
本文介绍了使用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#中使用字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆