I have the list of objects. For the simplicity, let's say objects are strings.
var strList = new List<object>() { "one", "two", "three" };
I would like to generate all distinct pairs. If I have a pair ("one" & "two")
I should not have also the pair ("two" & "one")
.
This is the code I use:
var pairs = strList.SelectMany(x => strList, (x, y) =>
Tuple.Create(x, y)).Where(x => x.Item1 != x.Item2);
foreach (var pair in pairs)
Console.WriteLine(pair.Item1 + " & " + pair.Item2);
Output:
one & two
one & three
two & one
two & three
three & one
three & two
Desired output:
one & two
one & three
two & three
Is there any simple way to accomplish that using LINQ?
Update:
Please before mark this question as duplicate consider that I am looking for a solution using LINQ which will apply to a list of any objects, regardless of CompareTo
is defined for it or not.
Solution:
If someone will come across to this question finally, I found the simple solution:
var pairs = strList.SelectMany(x => strList, (x, y) => Tuple.Create(x, y)).
Where(x => strList.IndexOf(x.Item1) < strList.IndexOf(x.Item2));