Remove duplicates in the list using linq

前端 未结 11 1643
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 03:04

I have a class Items with properties (Id, Name, Code, Price).

The List of Items is populated with duplicated items.

F

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:48

    var distinctItems = items.Distinct();
    

    To match on only some of the properties, create a custom equality comparer, e.g.:

    class DistinctItemComparer : IEqualityComparer {
    
        public bool Equals(Item x, Item y) {
            return x.Id == y.Id &&
                x.Name == y.Name &&
                x.Code == y.Code &&
                x.Price == y.Price;
        }
    
        public int GetHashCode(Item obj) {
            return obj.Id.GetHashCode() ^
                obj.Name.GetHashCode() ^
                obj.Code.GetHashCode() ^
                obj.Price.GetHashCode();
        }
    }
    

    Then use it like this:

    var distinctItems = items.Distinct(new DistinctItemComparer());
    

提交回复
热议问题