去除重复类型对象BookInfo示例:
bookList = bookList.Distinct(new DataRowComparer()).ToList(); //去除重复书籍////// 自定义书籍比较(去重)/// public class DataRowComparer : IEqualityComparer{ 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 IEnumerableDistinct (this IEnumerable source, Func keySelector) { HashSet seenKeys = new HashSet (); foreach (TSource element in source) { var elementValue = keySelector(element); if (seenKeys.Add(elementValue)) { yield return element; } } } }
去除单一类型元素:
Listlist = new List ();list.Add("a");list.Add("a");list.Add("b");list.Add("c");list.Add("b");list = list.Distinct().ToList();
扩展阅读: