Delete duplicates in a List of int arrays

前端 未结 8 1218
我寻月下人不归
我寻月下人不归 2020-12-30 00:25

having a List of int arrays like:

List intArrList = new List();
intArrList.Add(new int[3] { 0, 0, 0 });
intArrList.Add(new int[5] {         


        
8条回答
  •  我在风中等你
    2020-12-30 01:13

    Use GroupBy:

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

    The result:

    {0, 0, 0}

    {20, 30, 10, 4, 6}

    {1, 2, 5}

    {12, 22, 54}

    {1, 2, 6, 7, 8}

    {0, 0, 0, 0}

    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: To help understanding how the LINQ GroupBy solution works consider the following method:

    public List FindDistinctWithoutLinq(List lst)
    {
        var dic = new Dictionary();
        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();
    }
    

提交回复
热议问题