tags:

views:

272

answers:

2

I have a c# 3 HashSet object containing several elements. I want to check something between every pair of them, without repeating [(a,b)=(b,a)], and without pairing an element with itself.
I thought about switching to some sort of List, so I can pair each element with all of his following elements. Is there an option of doing something like that with a general, unordered, Collection? Or IQuaryable?

+2  A: 

How about using the Distinct method that takes an IEqualityComparer?

Mark Seemann
Maybe I'm missing something here, but how I can use an IEqualitycomparer to make sure all pairs are unique? I can easily use it to make sure an element won't pair with itself, but that is not enough...
Noam Gal
A HashSet only contains unique elements, you would have to create all tuples first. Seems overly complicated.
Henk Holterman
mm.. or maybe I can make the comparer for a pair of elements, and use it on a distinct over an IEnumerable of all pairs. I'll check it out later. thanks.
Noam Gal
+1  A: 

For this, it would be easier when you can access them with an index, and although there exists an ElementAt<> extension it probably is faster to use .ToList() first.

When you have an addressable list:

for (int i = 0; i < list.Count-1; i++)
  for (int j = i+1; j < list.Count; j++)
     Foo(list[i], list[j]);
Henk Holterman