C#LINQ查询字典 [英] C# LINQ query a Dictionary
本文介绍了C#LINQ查询字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C#词典:
Dictionary<int, ItemsClass> Items
ItemsClass
的成员名为编号
我想编写一个LINQ查询,该查询向我返回 ItemsClass
的字典键号具有与特定值匹配的 Number
,例如x。
I want to write a LINQ query that returns me the Dictionary key number for the ItemsClass
that has a Number
matching a certain value e.g. x.
我该怎么做?
推荐答案
要获取所有匹配项,您会使用:
To get all matching items you would use:
Items.Where(p => p.Value.Number == x).Select(p => p.Key);
要获得唯一的密钥,您总是希望它找到一个,并且只有一个:
To get the only key it you always expect it to find one, and only one:
Items.Where(p => p.Value.Number == x).Select(p => p.Key).Single();
如果有多个项目,则要获取第一个匹配项:
To get the first matching item, if there are multiple items:
Items.Where(p => p.Value.Number == x).Select(p => p.Key).First();
这篇关于C#LINQ查询字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文