sobota, 29 października 2016

LINQ - Convert List to Dictionary with Value as List

I have a List<MyObject> that I retrieve from the database.

I would like it keyed by a property in MyObject for grouping purposes.
What is the best way with LINQ to cast my list to: Dictionary<long, List<MyObject>>

Answear:

List<MyObject> list = ...;

var map = list
  .GroupBy(x => x.KeyedProperty)
  .ToDictionary(x => x.Key, x => x.ToList());

Brak komentarzy:

Prześlij komentarz