简体   繁体   English

多层列表上的C#LINQ Distinct()

[英]c# LINQ Distinct() on multi level list

I have a List<List<int>> with the following values: 我有一个具有以下值的List<List<int>>

[1] = 1,2
[2] = 4,5,6
[3] = 1,3

What I want to do is to retrieve simple List with unique values => 1,2,3,4,5,6 (number one was duplicated in original list). 我想做的是检索具有唯一值=> 1,2,3,4,5,6的简单列表(第一个在原始列表中重复)。

If it was 1D List, I would use 如果是一维列表,我会使用

variable.Select(n=>n).Distinct();

however when I tried to use 但是当我尝试使用

variable.Select(n=>n.Select(x=>x)).Distinct();

I got 2D list (with unique values I guess). 我得到了2D列表(我猜有唯一的值)。 How can I solve this? 我该如何解决? Thanks 谢谢

You could just use SelectMany with Distinct 您可以将SelectManyDistinct

var uniqueList = list.SelectMany(x => x).Distinct().ToList();

SelectMany flattents the List<List<int>> into a IEnumerable<int> and Distinct eliminates the duplicates. SelectManyList<List<int>>IEnumerable<int>Distinct消除了重复项。

private static void Main()
{
    List<List<int>> xss = new List<List<int>>()
    {
        new List<int>() {1, 2},
        new List<int>() {4, 5, 6},
        new List<int>() {1, 3}
    };
    var xs = xss.SelectMany(x => x).Distinct();
    Console.WriteLine(string.Join(" ",xs));
}

You could do SelectMany if you want a distinct of your overall integers, but if you want distinc lists, you could do something like this; 如果您希望整体整数与众不同,则可以执行SelectMany ,但是如果要使用distinc列表,则可以执行以下操作:

void Main()
{
    List<List<int>> xss = new List<List<int>>()
    {
        new List<int>() {1, 2},
        new List<int>() {1, 2},
        new List<int>() {1, 2},
        new List<int>() {4, 5, 6},
        new List<int>() {1, 3}
    };

    xss.Select (x => string.Join(",", x)).Distinct();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM