當一個結合中想根據某一個字段做去重方法時使用以下代碼
IQueryable 繼承自IEnumerable
先舉例:
#region linq to object List<People> peopleList = new List<People>(); peopleList.Add(new People { UserName = "zzl", Email = "1" }); peopleList.Add(new People { UserName = "zzl", Email = "1" }); peopleList.Add(new People { UserName = "lr", Email = "2" }); peopleList.Add(new People { UserName = "lr", Email = "2" }); Console.WriteLine("用擴展方法可以過濾某個字段,然后把當前實體輸出"); peopleList.DistinctBy(i => new { i.UserName }).ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email)); Console.WriteLine("默認方法,集合中有多個字段,當所有字段發生重復時,distinct生效,這與SQLSERVER相同"); peopleList.Select(i => new { UserName = i.UserName, Email = i.Email }).OrderByDescending(k => k.Email).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email)); Console.WriteLine("集合中有一個字段,將這個字段重復的過濾,並輸出這個字段"); peopleList.Select(i => new { i.UserName }).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName)); #endregion
該擴展方法貼出:
public static class EnumerableExtensions { public static IEnumerable<TSource> DistinctBy<TSource, Tkey>(this IEnumerable<TSource> source, Func<TSource, Tkey> keySelector) { HashSet<Tkey> hashSet = new HashSet<Tkey>(); foreach (TSource item in source) { if (hashSet.Add(keySelector(item))) { yield return item; } } } }
