LINQ: Tips and Tricks

Tip 1: How to convert a list of objects into a Dictionary?

For example, you have an List where Person contains field Name and field Age. Let's say that you want to create a Dictionary that would contain name and age of each person in a list. Traditionally, you would approach this problem by writing something like this:

private Dictionary<string, int> CovertToDictionary (List<Person> people) {
  Dictionary<string, int> retVal = new Dictionary<string, int> (people.Count);
  // version 1
  for (int i = 0; i < people.Count; i++) {
    retVal.Add(people[i].Name, people[i].Age);
  }
  // version 2
  foreach (Person p in people) {
    retVal.Add(p.Name, p.Age);
  }
  return retVal;
}

Well... That's all good, but there's a lot of code to do a simple task. Here's how LINQ can help:

private Dictionary<string, int> CovertToDictionary (List<Person> people) {
  return people.ToDictionary(p => p.Name, p=> p.Age);
}

Easy, huh? :)

Tip 2: How to find how many objects have a certain attribute set to a certain value?

Suppose you have a List where Person is an object that has property Name and property Gender and you want to find out how many people are Male. Here's what you do:

private int FindCount (List<Person> people, string gender) {
  int count = (from p in people
               where p.Gender.Equals(gender)
               select p).Count;
  return count;
}

Comments