Shane
Shane

Reputation: 4315

How do I select a List from something like new Dictionary(int, List<Customer>);

Dictionary<int, List<Customer>> dictionary = new Dictionary<int, List<Customer>>();

I want to query based on the key and get a List back. Not sure how to structure the LINQ query for that.

Desired Output:

A List<Customer> for a particular key in the Dictionary.

Upvotes: 1

Views: 282

Answers (2)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

You don't need to use LINQ for this, but if you really want to

int key = 1;
List<Customer> customers = dictionary.Single(item => item.Key == key).Value;

The simplest way is to just retrieve the value for the key using the regular [] operator

dictionary[key];

Upvotes: 1

Kirk Woll
Kirk Woll

Reputation: 77596

That's what the Dictionary (as you've defined the generic arguments) will do. So, dictionary[key] will return the list. Note that it will throw an exception if you haven't initialized it already with dictionary[key] = new List<Customer>();.

Upvotes: 4

Related Questions