0

I have a big list of certain objects that are of type Order. Furthermore, I have defined an IEqualityComparer<Order> and my goal is to efficiently create a list of lists (or groupings) where every sublist contains the objects that are equal to each other. Mathematically, I have an equivalence relation (IEqualityComparer) and want to have a list of all equivalence classes. I thought about using HashSet<Order>, Dictionary<> or Lookup<> but they dont seem to be perfect for my case. So any ideas?

T_D
  • 1,688
  • 1
  • 17
  • 28
  • The `ToLookup` should be perfect for this. – xanatos Jun 19 '15 at 12:32
  • 1
    `var grouped = sequence.ToLookup(x => x.Whatever, comparer);` - it simply could be `.ToLookup(x => x, comparer)` in your case – Marc Gravell Jun 19 '15 at 12:33
  • Maybe I am confused that Lookup needs a key and I dont care about it. So you propose to choose whatever as a key and dont mind further about it? – T_D Jun 19 '15 at 12:34
  • @T_D you already *chose* what to use as a key when you made an `IEqualityComparer` - that **defines**: "I'm using `Order` as the key". Since it is the key you will be comparing, if you want to use a different key, you'll need a suitable comparer. That could be an `IEqualityComparer` for example (there are lots inbuilt), using `x => x.Foo` – Marc Gravell Jun 19 '15 at 12:36

1 Answers1

0

I think this something like this shluod to the job:

var uniqueItems = yourRawList.Distinct(yourComparer);
var result = uniqueItems.Select(i => new List<Order>(yourRawList.Where(o =>yourComparer.Equals(i, o))));
0xBADF00D
  • 980
  • 1
  • 12
  • 25