【问题标题】:How to remove List<int[]> from another List<int[]>如何从另一个 List<int[]> 中删除 List<int[]>
【发布时间】:2015-06-23 18:19:48
【问题描述】:

这是我上一个问题的结果 How to remove int[] from List<int[]>?

我现在正在尝试删除 List int[] 中的 int[] 列表。

int[] t1 = new int[] { 0, 2 };
        List<int[]> trash = new List<int[]>()
        {
            t1,
            new int[] {0,2},
            new int[] {1,0},
            new int[] {1,1}
        };
        List<int[]> trash2 = new List<int[]>()
        {
            new int[] {0,1},
            new int[] {1,0},
            new int[] {1,1}
        };

        MessageBox.Show(trash.Count + "");
        trash.RemoveRange(trash2);
        MessageBox.Show(trash.Count + "");

我尝试将trash2 中的所有int[] 添加到trash 数组中,然后从trash2 数组中删除具有相同值的项目,但是它只从trash2 中删除了第一个int[]。

他们还有其他从 List 数组中删除 List 数组的方法吗?

【问题讨论】:

  • 您的样本的预期输出是什么?
  • @DimiToulakis,您是否尝试使用数组作为元素类型?
  • 我想删除所有与第二个数组的 int[] 值相同的 int[]。换句话说,我想从两个 List int[] 之间的差异中获得一个 int[] 列表
  • 我建议使用.Except 和为int[] 编写的IEqualityComparer
  • 列表中的顺序是否相关?数组中的顺序是否相关?您应该显示示例的预期结果。

标签: c# arrays list


【解决方案1】:

这是你的答案

int[] t1 = new int[] { 0, 2 };
List<int[]> trash = new List<int[]>()
{
    t1,
    new int[] {0,2},
    new int[] {1,0},
    new int[] {1,1}
};
List<int[]> trash2 = new List<int[]>()
{
    new int[] {0,1},
    new int[] {1,0},
    new int[] {1,1}
};

Console.WriteLine(trash.Count + "");//Count = 4
trash.RemoveAll(a => trash2.Any(b => b.SequenceEqual(a)));
Console.WriteLine(trash.Count + "");//Count = 2

之前的回答https://stackoverflow.com/a/30997772/1660178

中提到了一些SequenceEqual逻辑

【讨论】:

  • 在包含我上一篇文章的给定链接上。有人提出了这个答案但承认这比其他方法慢,但感谢您的回答:D
【解决方案2】:

另一种方法涉及使用.Except 扩展方法和自定义IEqualityComparer。下面的代码也会产生你需要的结果:

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

    public int GetHashCode(int[] x)
    {
        return x.Aggregate((t,i) => t + i.GetHashCode());
    }
}  

class Program
{
    static void Main(string[] args)
    {
        int[] t1 = new int[] { 0, 2 };
        List<int[]> trash = new List<int[]>()
        {
            t1,
            new int[] {0,2},
            new int[] {1,0},
            new int[] {1,1}
        };

        List<int[]> trash2 = new List<int[]>()
        {
            new int[] {0,1},
            new int[] {1,0},
            new int[] {1,1}
        };

        var difference = trash.Except(trash2, new IntArrayComparer()).ToArray();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 2012-06-07
    • 2012-09-28
    • 2017-12-11
    • 1970-01-01
    • 2015-09-22
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多