c#list集合根据某个字段去重_完美解决c#distinct不好⽤的问题当⼀个结合中想根据某⼀个字段做去重⽅法时使⽤以下代码
IQueryable 继承⾃IEnumerable
先举例:
#region linq to object
List peopleList = new List();
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 DistinctBy(this IEnumerable source, Func keySelector)
{
HashSet hashSet = new HashSet();
foreach (TSource item in source)
{
if (hashSet.Add(keySelector(item)))
{
yield return item;
}
}
}
}
补充知识:c# – .Distinct()调⽤不过滤
我正在尝试使⽤AsEnumerable将Entity Framework DbContext查询拉⼊IEnumerable< SelectListItem>.这将⽤作填充视图中下拉列表的模型属性.
但是,尽管调⽤了Distinct(),但每个查询都会返回重复的条⽬.
public IEnumerable StateCodeList { get; set; }
public IEnumerable DivCodeList { get; set; }
DivCodeList =
db.MarketingLookup.AsEnumerable().OrderBy(x => x.Division).Distinct().Select(x => new SelectListItem
{
distinct查询
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不好⽤的问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持WEB开发者。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。