简体   繁体   English

区别清单 <List<int> &gt;?

[英]Distinct List<List<int>>?


I have a problem with getting only the distinct lists. 我仅获取不重复列表有问题。
So I have : 所以我有 :

List<List<int>> combinations = new List<List<int>>();
combinations.Add(new List<int> {1,1});
combinations.Add(new List<int> {1,2});
combinations.Add(new List<int> {1,1}); // Same
combinations.Add(new List<int> {1,3});

What I need to do is to get only : 我需要做的只是获得:

{1,1}
{1,2}
{1,3}

I tried with this : combinations = combinations.Distinct().ToList(); 我尝试过这样的方法: combinations = combinations.Distinct().ToList(); But it does not work. 但这行不通。
Any ideas. 有任何想法吗。 Thank you in advance. 先感谢您。

You can use your own comparer: 您可以使用自己的比较器:

var distincts = 
    combinations
    .Distinct(new ListOfIntComparer());    

class ListOfIntComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> a, List<int> b)
    {
        return
            a.SequenceEqual(b);
    }

    public int GetHashCode(List<int> l)
    {
        unchecked
        {
            int hash = 19;
            foreach (var foo in l)
            {
                hash = hash * 31 + foo.GetHashCode();
            }
            return hash;
         }
    }
}

GetHasCode() implementation from Jon Skeet here . GetHasCode()从乔恩斯基特执行这里

Trying to come up with the shortest oneliner. 试图提出最短的oneliner。 This is what i come up with. 这就是我想出的。 Hope it helps you. 希望对您有帮助。

var unique = combinations.GroupBy(x => string.Join(",", x), (g, items) => items.First());

Try adding a regular int array: 尝试添加常规的int数组:

List<List<int>> lli = new List<List<int>>();

lli.Add((new int[] { 2, 4 }).ToList<int>());

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

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