Remove duplicates in the list using linq

前端 未结 11 1458
没有蜡笔的小新
没有蜡笔的小新 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:39

    An universal extension method:

    public static class EnumerableExtensions
    {
        public static IEnumerable DistinctBy(this IEnumerable enumerable, Func keySelector)
        {
            return enumerable.GroupBy(keySelector).Select(grp => grp.First());
        }
    }
    

    Example of usage:

    var lstDst = lst.DistinctBy(item => item.Key);
    

提交回复
热议问题