130

I have a

List<MyObject> 

that I retrieve from the database. However, 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>>

I have the following:

myObjectList.ToDictionary(x => x.KeyedProperty)

But it returns:

Dictionary<long, MyObject>
1
  • You want the dictionary keyed to a propery of WHICH MyObject? -- you have a whole list of them.... Commented Aug 23, 2010 at 15:41

2 Answers 2

256

It sounds like you want to group the MyObject instances by KeyedProperty and put that grouping into a Dictionary<long,List<MyObject>>. If so then try the following

List<MyObject> list = ...;
var map = list
  .GroupBy(x => x.KeyedProperty)
  .ToDictionary(x => x.Key, x => x.ToList());
Sign up to request clarification or add additional context in comments.

Comments

20

You should use the ToLookup extension method on the Enumerable class like so:

List<MyObject> list = ...;

ILookup<long, MyObject> lookup = list.ToLookup(o => o.KeyedProperty);

If you want to place that in a dictionary, then you could use the ToDictionary extension method, like so:

IDictionary<long, IEnumerable<MyObject>> dictionary = lookup.ToDictionary(
    l => l.Key);

4 Comments

What's the difference between this and the accepted answer? Does the ILookup preserve references whereas the accepted answer does not?
@PatPeter The idea is that when you have a one-to-many relationship between the key and the items, a Lookup<TKey, TValue> may be a better structure than a Dictionary<TKey, TValue>.
@PatPeter i would say the ILookup is the better structure to use (its like multimap to dictonary's map, if you know C++ collection algorithms) but it has one big factor to bear in mind - the lookup created is immutable. You cannot add or remove entries afterwards.
The other consideration is that even though ILookup is often the ideal in-code structure, it often isn't handled well for serialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.