1

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?

Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24
Harry Boy
  • 4,159
  • 17
  • 71
  • 122

1 Answers1

4

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();
Sean
  • 60,939
  • 11
  • 97
  • 136
  • 1
    Minor correction: From my reading it would be `p.Value.Number == x`. Also may also be worth using `Single` or `SingleOrDefault` since the implication is that there is only a single result expected rather than multiple possible. – Chris Jun 08 '16 at 13:01
  • Ensure you have System.Linq using statement included at the top. – VivekDev Oct 25 '18 at 10:25