Daniel
Daniel

Reputation: 155

List to Dictionary conversion using Linq

Can somebody suggest me what Linq operator should I use to write an elegant code to convert List to Dictionary of list? Eg. I have a list of person (List<Person>) and I wanted to convert that to dictionary of list (like Dictionary<string, List<Person>> using the person's last name as a key. I needed that for quickly lookup the list of persons by the last name

Upvotes: 3

Views: 3381

Answers (3)

xanatos
xanatos

Reputation: 111940

This isn't what you asked for, but you can use Philip response for that :-)

var lookup = myList.ToLookup(p => p.Surname);

This will create an ILookup<string, Person> that is something very similar to what you wanted (you won't have a Dictionary<string, List<Person>> but something more similar to a Dictionary<string, IEnumerable<Person>> and and the ILookup is readonly)

Upvotes: 3

you can also use as follows.

foreach(var item in MyList)
 {  
   if(!myDictionary.Keys.Contains(item))
     myDictionary.Add(item,item.value);
 } 

Upvotes: 0

Philip
Philip

Reputation: 694

To get a Dictionary<string, List<Person>> from List<Person>:

var dictionary = list
                   .GroupBy(p => p.LastName)
                   .ToDictionary(g => g.Key, g => g.ToList());

Upvotes: 7

Related Questions