简体   繁体   中英

C# LINQ query a Dictionary

I have a C# dictionary:

Dictionary<int, ItemsClass> Items

ItemsClass has a member called 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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