Remove duplicate inner lists from a list of list<object> in c#

前端 未结 2 1903
不知归路
不知归路 2020-12-21 14:49

I apologize for the ambiguous title. I couldn\'t keep it clear and concise at the same time. So feel free to change it.

I have a big List which contains several othe

2条回答
  •  爱一瞬间的悲伤
    2020-12-21 14:59

    I would implement a custom IEqualityComparer> which you can use for Distinct:

    public class ColumnListComparer : IEqualityComparer>
    {
        public bool Equals(IEnumerable x, IEnumerable y)
        {
            if (x == null || y == null) return false;
            if (object.ReferenceEquals(x, y)) return true;
            return x.SequenceEqual(y);
        }
    
        public int GetHashCode(IEnumerable obj)
        {
            unchecked
            {
                int hash = 17;
                foreach(Column col in obj)
                {
                    hash = hash * 23 + (col == null ? 0 : col.GetHashCode());
                }
                return hash;
            }
        }
    }
    

    Now this works:

    var result = listOfAllColumns.Distinct(new ColumnListComparer());
    

    You also need to override Equals + GetHashCode in your class Column:

    public class Column
    {
        public string SectionName;
        public string StirrupType;
        public int StirrupSize;
        public double StirrupSpacing;
    
        public override bool Equals(object obj)
        {
            Column col2 = obj as Column;
            if(col2 == null) return false;
            return SectionName    == col2.SectionName
                && StirrupType    == col2.StirrupType 
                && StirrupSize    == col2.StirrupSize
                && StirrupSpacing == col2.StirrupSpacing;
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + (SectionName ?? "").GetHashCode();
                hash = hash * 23 + (StirrupType ?? "").GetHashCode();
                hash = hash * 23 + StirrupSize.GetHashCode();
                hash = hash * 23 + StirrupSpacing.GetHashCode();
                return hash;
            }
        }
    }
    

提交回复
热议问题