Linq and grouping with custom object<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Linq and grouping with custom object

Posted on: December 3, 2012

Depending of what you want to do, you may want to group by id or by more values. A common case is to group by a unique idenfier but also want to get some connexe information like let say having the name. For example, if we want to group every jobs that every body had in their life, we would like to group by userid. But we may want to have their full name.

1var groupedList = nonGroupedList.GroupBy(g=> new MyCustomGroupingClass(g.UserId, g.UserFullName));

This won't work because every MyCustomGroupingClass will be different from C# perspective. This is because Linq will compare every object and figure out that every MyCustomGroupingClass has a different object.

1var groupedList = nonGroupedList.GroupBy(g=> g.UserId);

This would work, because an integer is comparable but it doesn't solve the need to have the user name.

The solution is hidden in the problem : comparing classes. We need to provide a way to compare. This can be done by providing an override to the Equals method of your grouping class.

1public class MyCustomGroupingClass {
2 public int ID { get; set; }
3 public string FullName { get; set; }
5 public override bool Equals(object obj) {
6 if (ReferenceEquals(null, obj))
7 return false;
8 if (ReferenceEquals(this, obj))
9 return true;
10 if (obj.GetType() != this.GetType())
11 return false;
13 return Equals((MyCustomGroupingClass)obj);
14 }
16 protected bool Equals(MyCustomGroupingClass other) {
17 return ID.Equals(other.ID) && string.Equals(FullName, other.FullName);
18 }

From here, you will be able to group without problem with Linq and your custom grouping class.