简体   繁体   English

C# LINQ 查询字典

[英]C# LINQ query a Dictionary

I have a C# dictionary:我有一个 C# 字典:

Dictionary<int, ItemsClass> Items

ItemsClass has a member called Number ItemsClass有一个名为Number的成员

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 egx我想写一个LINQ查询,返回我的字典键数ItemsClass具有Number匹配某个值EGX

How can I do this?我该怎么做?

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM