完美解決c# distinct不好用的問題
當一個結(jié)合中想根據(jù)某一個字段做去重方法時使用以下代碼
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("默認方法,集合中有多個字段,當所有字段發(fā)生重復時,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()調(diào)用不過濾
我正在嘗試使用AsEnumerable將Entity Framework DbContext查詢拉入IEnumerable< SelectListItem>.這將用作填充視圖中下拉列表的模型屬性.
但是,盡管調(diào)用了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生效,如果類型是自定義類型,則序列必須包含實現(xiàn)IEquatable接口的類型的對象.
正如here所述:
Distinct returns distinct elements from a sequence by using the
default equality comparer to compare values.
一個解決方法,為了避免上述情況,因為我可以得出結(jié)論,你不需要整個對象而不是它的一個屬性,就是將序列的每個元素投影到Division,然后創(chuàng)建OrderBy并調(diào)用Distinct :
var divisions = db.MarketingLookup.AsEnumerable()
.Select(ml=>ml.Division)
.OrderBy(division=>division)
.Distinct()
.Select(division => new SelectListItem
{
Text = division,
Value = division
}).ToList();
有關(guān)此問題的進一步文檔,請查看here.
以上這篇完美解決c# distinct不好用的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#實現(xiàn)winform自動關(guān)閉MessageBox對話框的方法
這篇文章主要介紹了C#實現(xiàn)winform自動關(guān)閉MessageBox對話框的方法,實例分析了C#中MessageBox對話框的相關(guān)操作技巧,需要的朋友可以參考下2015-04-04
C#函數(shù)式編程中的遞歸調(diào)用之尾遞歸詳解
這篇文章主要介紹了C#函數(shù)式編程中的遞歸調(diào)用詳解,本文講解了什么是尾遞歸、尾遞歸的多種方式、尾遞歸的代碼實例等內(nèi)容,需要的朋友可以參考下2015-01-01
深入C#中使用SqlDbType.Xml類型參數(shù)的使用詳解
本篇文章是對在C#中使用SqlDbType.Xml類型參數(shù)的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05

