简体   繁体   中英

How to remove List<int[]> from another List<int[]>

This is the aftermath from my previous question How to remove int[] from List<int[]>?

I'm now trying remove a list of int[]s inside a List 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 + "");

I tried to add all the int[] from trash2 to trash array and then removed items with the same value from the trash2 array but, it only remove the first int[]s from the trash2.

is their any other way of removing List arrays from List arrays?

here is your answer

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

Some SequenceEqual logic is mentioned in previous answer https://stackoverflow.com/a/30997772/1660178

Another approach involves the use of the .Except extension method, and a custom IEqualityComparer . The following code also produces the result you need:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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