Comparing each element with each other element in a list
It sounds like you might want 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 definitely 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 - 1)
select Tuple.Create(list[i], list[j]);
I'm not sure it's any clearer though...
EDIT: Another alternative which is less efficient, but potentially clearer:
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);
If you are using C# 7 or later, you can take advantage of the ValueTuple
type. It offers increased usability and performance.
public static IEnumerable<(T, T)> GetAllPairs<T>(IList<T> source)
{
return source.SelectMany((_, i) => source.Where((_, j) => i < j),
(x, y) => (x, y));
}
Usage example:
foreach ((int x, int y) in GetAllPairs(new[] { 0, 1, 2 }))
{
// Execute code
Console.WriteLine($"Pair: {x}, {y}");
}
Output:
Pair: 0, 1
Pair: 0, 2
Pair: 1, 2