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
?
views:
272answers:
2
+2
A:
How about using the Distinct method that takes an IEqualityComparer?
Mark Seemann
2009-07-28 11:03:38
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
2009-07-28 11:26:46
A HashSet only contains unique elements, you would have to create all tuples first. Seems overly complicated.
Henk Holterman
2009-07-28 11:27:50
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
2009-07-28 11:28:50
+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
2009-07-28 11:24:15