完美解決c# distinct不好用的問題
阿新 • • 發佈:2020-12-08
當一個結合中想根據某一個欄位做去重方法時使用以下程式碼
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; } } } }
補充知識:c# – .Distinct()呼叫不過濾
我正在嘗試使用AsEnumerable將Entity Framework DbContext查詢拉入IEnumerable< SelectListItem>.這將用作填充檢視中下拉列表的模型屬性.
但是,儘管呼叫了Distinct(),但每個查詢都會返回重複的條目.
public IEnumerable<SelectListItem> StateCodeList { get; set; } public IEnumerable<SelectListItem> DivCodeList { get; set; } DivCodeList = db.MarketingLookup.AsEnumerable().OrderBy(x => x.Division).Distinct().Select(x => new SelectListItem { Text = x.Division,Value = x.Division }).ToList(); StateCodeList = db.MarketingLookup.AsEnumerable().OrderBy(x => x.State).Distinct().Select(x => new SelectListItem { Text = x.State,Value = x.State }).ToList();
為了使Distinct生效,如果型別是自定義型別,則序列必須包含實現IEquatable介面的型別的物件.
正如here所述:
Distinct returns distinct elements from a sequence by using the
default equality comparer to compare values.
一個解決方法,為了避免上述情況,因為我可以得出結論,你不需要整個物件而不是它的一個屬性,就是將序列的每個元素投影到Division,然後建立OrderBy並呼叫Distinct :
var divisions = db.MarketingLookup.AsEnumerable() .Select(ml=>ml.Division) .OrderBy(division=>division) .Distinct() .Select(division => new SelectListItem { Text = division,Value = division }).ToList();
有關此問題的進一步文件,請檢視here.
以上這篇完美解決c# distinct不好用的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。