Search code examples
c#linqgroup-byhashsetiequalitycomparer

Custom IEqualityComparer<T> for HashSet and other Objects


I am using LINQ and doing a group by using multiple objects. One of these objects is a HashSet.

var group = map.GroupBy(m => new{m.Item2.Clients,m.Item3,m.Item2.StartTimeID});

Where m.Item2.ClientCampaigns is of type HashSet, m.Item3 is a seperate class that methods for GetHashCode and Equals methods m.Item2.StartTimeId is of type INT

Now I need to do a GROUP BY on these three, by passing in a custom IEquality Comparer I guess?

If it was just HasSet, I could use HashSet<ClientCampaign>.CreateSetComparer() as the second argument in the GroupBy method.

In this case, what should I use?


Solution

  • I solved it! I created a new class with all the parameters, I am grouping by. I have created a new custom Comparer that extends from IEqualityComparer. This custom comparer must have public bool Equals and public int GetHashCode methods respectively. And, Then I used this Comparer in the GroupBy clause I have in the code.