Harry Boy
Harry Boy

Reputation: 4747

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 e.g. x.

How can I do this?

Upvotes: 1

Views: 11555

Answers (1)

Sean
Sean

Reputation: 62472

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

Upvotes: 4

Related Questions