去除重复类型对象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删除重复数据时如何指定所要依据的成员属性

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
猜你喜欢
  • 2022-01-28
  • 2022-12-23
  • 2021-06-07
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案