0

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));
L_J
  • 2,351
  • 10
  • 23
  • 28
  • I do not see how this question is duplicate of the referred one. The question is not about "all combinations" it's about all distinct combinations. Part one of the answers to the referred (K-combinations) looks related to this question. However, there is a significant difference, which could not be applied here. It uses the `CompareTo` which cannot be used here for any objects. – L_J Jun 29 '18 at 11:46
  • That's probably because you don't read all answers. – Gert Arnold Jun 29 '18 at 12:21
  • @GertArnold I look at all the answers but could not see the one which fits my problem. Could you please indicate which one you mean? – L_J Jun 29 '18 at 12:31

0 Answers0