完美解决c# distinct不好用的问题

编辑: admin 分类: c#语言 发布时间: 2022-03-12 来源:互联网

当一个结合中想根据某一个字段做去重方法时使用以下代码

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不好用的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持海外IDC网。