group list by condition to create list of lists

Viewed 289

I have a List<type1> listOfObjects and a static method

bool CheckIfObjectsAreEquivalent(type1 obj1, type1 obj2).

I would like to group the list by the equivalence criteria, i.e. have List<List<type1>> result where each list consists of the objects that are equivalent according to CheckIfObjectsAreEquivalent.

Another important aspect is, that I do not know upfront how many different lists will result from this grouping, as all objects could be equivalent or none or any possible number of equivalence groups. The initial list of objects listOfObjects can consist of variously many objects and to see if two of those objects are equivalent one must use CheckIfObjectsAreEquivalent.

I've been looking into different options using .Where and .GroupBy but I can't get it to work...

Any ideas? Thanks in advance

1 Answers

You can implement IEqualityComparer<type1> interface and then use the implementation in GroupBy:

public sealed class MyEqualityComparer : IEqualityComparer<type1> {
  public bool Equals(type1 x, type1 y) {
    // Your method here
    return MyClass.CheckIfObjectsAreEquivalent(x, y);
  }

  public int GetHashCode(type1 obj) {
    //TODO: you have to implement HashCode as well
    // return 0; is the WORST possible implementation
    // However the code will do for ANY type (type1)
    return 0; 
  }
}

Then you can put:

var result = listOfObjects
  .GroupBy(item => item, new MyEqualityComparer())
  .Select(chunk => chunk.ToList()) // Let's have List<List<type1>> 
  .ToList();
Related