tags:

views:

54

answers:

2
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.

+4  A: 

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

Kirk Woll
Seems like OP wants the answer using LINQ? Surely not this simple.
Steve Townsend
@Steve, I suppose, but forcibly using LINQ to exercise the native semantics of a Dictionary seems bizarre.
Kirk Woll
Why overcomplicate it?
Bennor McCarthy
yeah, it was this simple. Was doing LINQ to further par down the List and getting myself confused for a moment. This works.
Shane
@Kirk/Shane - agreed - nice when it's a simple answer
Steve Townsend
+1  A: 

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];
Kirk Broadhurst
this syntax would helpful in the future too, as i'm going to be doing a lot of Dictionary operations. Thanks!
Shane