Wednesday, February 10, 2010

Quickly create a Dictionary using Linq to Objects

When working with collections or lists, sometimes you just need to get a simple dictionary.
There are a number of ways to do this, but the ToDictionary method seems promising.
For isntance:

   1:  IList<Person> people = new List<Person>();
   2:  people.Add(new Person 
   3:      {
   4:          FirstName = "Jim", 
   5:          LastName="Schubert", 
   6:          Age=29, 
   7:          Phone="123-333-4444"
   8:      });
   9:  people.Add(new Person 
  10:      {
  11:          FirstName = "Joe", 
  12:          LastName="Schubert", 
  13:          Age=25, 
  14:          Phone="800-999-1111"
  15:      });
  16:      
  17:  Dictionary<int,string> names = people.ToDictionary(k => k.Age, v => v.FirstName);


There may not be many uses for this type of syntax, but simple transformations like this make Linq fun.

No comments:

Archive