I Prefer Jim Developer James Schubert shares his code and his thoughts.

10Feb/10Off

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:

  IList<Person> people = new List<Person>();
  people.Add(new Person
      {
          FirstName = "Jim",
          LastName="Schubert",
          Age=29,
          Phone="123-333-4444"
      });
  people.Add(new Person
       {
           FirstName = "Joe",
           LastName="Schubert",
           Age=25,
           Phone="800-999-1111"
       });

   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.

Related posts:

  1. Useful Serialization Methods of LINQ to SQL objects
  2. Displaying multiple fields in a Dropdownlist’s DataTextField

flattr this!

Tagged as: , , Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.