开发者

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

开发者 https://www.devze.com 2023-01-16 18:45 出处:网络
开发者_开发百科Dictionary<int, List<Customer>> dictionary = 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.


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


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消