C#去除List中集合的重复项(类型对象和单一类型)

时间:2025-05-11 00:08:08

去除重复类型对象BookInfo示例:

bookList = bookList.Distinct(new DataRowComparer()).ToList(); //去除重复书籍

/// <summary>
/// 自定义书籍比较(去重)
/// </summary>
public class DataRowComparer : IEqualityComparer<BookInfo>
{
public bool Equals(BookInfo b1, BookInfo b2)
{
return (b1.BookId == b2.BookId); //去重
}
public int GetHashCode(BookInfo b)
{
return b.ToString().GetHashCode();
}
}

推荐使用这种:

 return list.Distinct(o => o.Id).ToList();//去重
    public static class EnumerableExtender
{
public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
var elementValue = keySelector(element);
if (seenKeys.Add(elementValue))
{
yield return element;
}
}
}
}

去除单一类型元素:

List<string> list = new List<string>();
list.Add("a");
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("b");
list = list.Distinct().ToList();

扩展阅读:

Linq使用Distinct删除重复数据时如何指定所要依据的成员属性