Noam Gal
Noam Gal

Reputation: 3405

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

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?

Upvotes: 4

Views: 2375

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

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]);

Upvotes: 5

Mark Seemann
Mark Seemann

Reputation: 233135

How about using the Distinct method that takes an IEqualityComparer?

Upvotes: 2

Related Questions