删除int数组列表中的重复项 [英] Delete duplicates in a List of int arrays

查看:78
本文介绍了删除int数组列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有int数组的列表,如:

having a List of int arrays like:

List<int[]> intArrList = new List<int[]>();
intArrList.Add(new int[3] { 0, 0, 0 });
intArrList.Add(new int[5] { 20, 30, 10, 4, 6 });  //this
intArrList.Add(new int[3] { 1, 2, 5 });
intArrList.Add(new int[5] { 20, 30, 10, 4, 6 });  //this
intArrList.Add(new int[3] { 12, 22, 54 });
intArrList.Add(new int[5] { 1, 2, 6, 7, 8 });
intArrList.Add(new int[4] { 0, 0, 0, 0 });

您将如何删除重复项(重复是指列表元素具有相同的长度和相同的编号).

How would you remove duplicates (by duplicate I mean element of list has same length and same numbers).

在示例中,我将删除元素{ 20, 30, 10, 4, 6 },因为它被两次发现

On the example I would remove element { 20, 30, 10, 4, 6 } because it is found twice

我当时正在考虑按元素大小对列表进行排序,然后使每个元素循环以保持静止,但我不确定如何做到这一点.

I was thinking on sorting the list by element size, then loop each element against rest but I am not sure how to do that.

另一个问题是,如果使用其他结构(例如哈希)会更好...如果可以,如何使用它?

Other question would be, if using other structure like a Hash would be better... If so how to use it?

推荐答案

使用

结果:

{0,0,0}

{0, 0, 0}

{20,30,10,4,6}

{20, 30, 10, 4, 6}

{1、2、5}

{12,22,54}

{12, 22, 54}

{1、2、6、7、8}

{1, 2, 6, 7, 8}

{0,0,0,0}

{0, 0, 0, 0}

编辑:如果要考虑{1,2,3,4}等于{2,3,4,1},则需要这样使用OrderBy:

EDIT: If you want to consider {1,2,3,4} be equal to {2,3,4,1} you need to use OrderBy like this:

var result = intArrList.GroupBy(p => string.Join(", ", p.OrderBy(c => c)))
                       .Select(c => c.First().ToList()).ToList(); 

EDIT2 :为了帮助理解LINQ GroupBy解决方案的工作方式,请考虑以下方法:

EDIT2: To help understanding how the LINQ GroupBy solution works consider the following method:

public List<int[]> FindDistinctWithoutLinq(List<int[]> lst)
{
    var dic = new Dictionary<string, int[]>();
    foreach (var item in lst)
    {
        string key = string.Join(",", item.OrderBy(c=>c));

        if (!dic.ContainsKey(key))
        {
            dic.Add(key, item);
        }
    }

    return dic.Values.ToList();
}

这篇关于删除int数组列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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