LINQ里的Distinct()

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;
}
}
}
}

转载于:https://www.cnblogs.com/niuzaihenmang/p/5620915.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值