Remove duplicates in the list using linq

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

    Try this extension method out. Hopefully this could help.

    public static class DistinctHelper
    {
        public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
        {
            var identifiedKeys = new HashSet();
            return source.Where(element => identifiedKeys.Add(keySelector(element)));
        }
    }
    

    Usage:

    var outputList = sourceList.DistinctBy(x => x.TargetProperty);
    

提交回复
热议问题