Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An easy way of iterating over all unique pairs in a collection

Tags:

c#

collections

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?

like image 868
Noam Gal Avatar asked Oct 20 '25 13:10

Noam Gal


1 Answers

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]);
like image 97
Henk Holterman Avatar answered Oct 22 '25 02:10

Henk Holterman