清单< C#从列表&LT删除重复INT>> [英] C# remove duplicates from List<List<int>>

查看:111
本文介绍了清单< C#从列表&LT删除重复INT>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有想出最有效的算法,从列表与LT删除重复的麻烦;列表< INT>> 为例(我知道这看起来像一个的 INT [] ,但只是在做这种方式视觉用途清单:

I'm having trouble coming up with the most efficient algorithm to remove duplicates from List<List<int>>, for example (I know this looks like a list of int[], but just doing it that way for visual purposes:

my_list[0]= {1, 2, 3};
my_list[1]= {1, 2, 3};
my_list[2]= {9, 10, 11};
my_list[3]= {1, 2, 3};

因此,输出将只是

new_list[0]= {1, 2, 3};
new_list[1]= {9, 10, 11};

让我知道,如果你有任何想法,我真的很感激它。

Let me know if you have any ideas. I would really appreciate it.

推荐答案

建立 EqualityComparer<定制;列表< INT>>

public class CusComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> x, List<int> y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<int> obj)
    {
        int hashCode = 0;

        for (var index = 0; index < obj.Count; index++)
        {
            hashCode ^= new {Index = index, Item = obj[index]}.GetHashCode();
        }

        return hashCode;
    }
}



然后你可以使用的鲜明,提供自定义比较方法:

Then you can get the result by using Distinct with custom comparer method:

var result = my_list.Distinct(new CusComparer());



编辑:

提供索引方法的GetHashCode ,以确保不同的订单将不等于

Include the index into method GetHashCode to make sure different orders will not be equal

这篇关于清单&LT; C#从列表&LT删除重复INT&GT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆