根据元素属性从列表中获取唯一元素

时间:2019-03-19 14:16:44

标签: c# list linq

如何基于属性string Name从列表中获取唯一元素? 我已经尝试过了,但是没有用。结果列表已排序并分组,但没有删除重复的元素:

List<ElementType> uniqueTypes = types.OrderBy(g => g.Name)
.GroupBy(g => g.Name).Select(s => s.First()).ToList();

任何帮助,非常感谢。

2 个答案:

答案 0 :(得分:1)

对扩展方法DistinctBy使用标准定义之一。这是我使用的几个:

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer = null) {
    var seenKeys = new HashSet<TKey>(comparer);
    foreach (var e in src)
        if (seenKeys.Add(keySelector(e)))
            yield return e;
}
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, Func<IGrouping<TKey, T>, T> pickOne, IEqualityComparer<TKey> comparer = null) =>
    src.GroupBy(keySelector).Select(g => pickOne(g));

答案 1 :(得分:0)

一种解决方案是创建List的副本,并在ElementType中实现Equals和GetHashCode(可以实现Equals,以便当仅属性名称相等时返回true),以便可以将仅元素添加到新列表中使用以下方法不在您的旧列表中:

if (newList.Contains(element))
    //remove element from the old list or you can check if !Contains and add the element to the new list