Comparing each item with another item in the list

What is the best way to write a control structure that will iterate over each combination of 2 items in a list?

Example:

{0,1,2} 

I want the code block to run three times, once on each of them:

 {0,1} {1,2} {0,2} 

I tried the following

 foreach (int i in input) { foreach (int j in input.Where(o => o != i)) { //Execute code } } 

However, this will not work if there are two identical items in the list. FROM

 {0,2,0} 

I would like to compare elements 0 and 0 . The value does not matter.

+7
source share
1 answer

It looks like you might need something like:

 for (int i = 0; i < list.Count - 1; i++) { for (int j = i + 1; j < list.Count; j++) { // Use list[i] and list[j] } } 

You can do this with LINQ:

 var pairs = from i in Enumerable.Range(0, list.Count - 1) from j in Enumerable.Range(i + 1, list.Count - i) select Tuple.Create(list[i], list[j]); 

I'm not sure this is clearer though ...

EDIT: Another alternative that is less effective but potentially more clear:

 var pairs = from i in Enumerable.Range(0, list.Count - 1) let x = list[i] from y in list.Skip(i + 1) select Tuple.Create(x, y); 
+21
source