c# list集合根据某个字段去重_完美解决c# distinct不好用的问题

时间:2025-01-24 20:16:46

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

IQueryable 继承自IEnumerable

先举例:

#region linq to object

List peopleList = new List();

(new People { UserName = "zzl", Email = "1" });

(new People { UserName = "zzl", Email = "1" });

(new People { UserName = "lr", Email = "2" });

(new People { UserName = "lr", Email = "2" });

("用扩展方法可以过滤某个字段,然后把当前实体输出");

(i => new { }).ToList().ForEach(i => ( + ));

("默认方法,集合中有多个字段,当所有字段发生重复时,distinct生效,这与SQLSERVER相同");

(i => new { UserName = , Email = }).OrderByDescending(k => ).Distinct().ToList().ForEach(i => ( + ));

("集合中有一个字段,将这个字段重复的过滤,并输出这个字段");

(i => new { }).Distinct().ToList().ForEach(i => ());

#endregion

该扩展方法贴出:

public static class EnumerableExtensions

{

public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)

{

HashSet hashSet = new HashSet();

foreach (TSource item in source)

{

if ((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 =

().OrderBy(x => ).Distinct().Select(x => new SelectListItem

{

Text = ,

Value =

}).ToList();

StateCodeList =

().OrderBy(x => ).Distinct().Select(x => new SelectListItem

{

Text = ,

Value =

}).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 = ()

.Select(ml=>)

.OrderBy(division=>division)

.Distinct()

.Select(division => new SelectListItem

{

Text = division,

Value = division

}).ToList();

有关此问题的进一步文档,请查看here.

以上这篇完美解决c# distinct不好用的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持WEB开发者。