Delete duplicates in a List of int arrays

前端 未结 8 1200
我寻月下人不归
我寻月下人不归 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:07

    You can define your own implementation of IEqualityComparer and use it together with IEnumerable.Distinct:

    class MyComparer : IEqualityComparer 
    {
        public int GetHashCode(int[] instance) { return 0; } // TODO: better HashCode for arrays
        public bool Equals(int[] instance, int[] other)
        {
            if (other == null || instance == null || instance.Length != other.Length) return false;
    
            return instance.SequenceEqual(other);
        }
    }
    

    Now write this to get only distinct values for your list:

    var result = intArrList.Distinct(new MyComparer());
    

    However if you want different permutations also you should implement your comparer this way:

    public bool Equals(int[] instance, int[] other)
    {
        if (ReferenceEquals(instance, other)) return true; // this will return true when both arrays are NULL
        if (other == null || instance == null) return false;
        return instance.All(x => other.Contains(x)) && other.All(x => instance.Contains(x));
    }
    

    EDIT: For a better GetashCode-implementation you may have a look at this post as also suggested in @Mick´s answer.

提交回复
热议问题