使用LINQ

时间:2018-06-28 14:24:01

标签: c# linq collections

我有对象列表。为了简单起见,假设对象是字符串。

    var strList = new List<object>() { "one", "two", "three" };

我想生成所有不同的对。如果我有一对("one" & "two"),我就不应该也有一对("two" & "one")

这是我使用的代码:

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

输出: one & two one & three two & one two & three three & one three & two

所需的输出: one & two one & three two & three

有没有简单的方法可以使用LINQ做到这一点?

更新: 在将此问题标记为重复之前,请考虑我正在寻找使用LINQ的解决方案,无论是否为CompareTo定义了该解决方案,该解决方案都将应用于所有对象的列表。

解决方案:

如果最终有人会遇到这个问题,我找到了简单的解决方案:

var pairs = strList.SelectMany(x => strList, (x, y) => Tuple.Create(x, y)).
    Where(x => strList.IndexOf(x.Item1) < strList.IndexOf(x.Item2));

0 个答案:

没有答案