码迷,mamicode.com
首页 > 其他好文 > 详细

LINQ里的Distinct()

时间:2016-06-27 19:19:15      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

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

LINQ里的Distinct()

标签:

原文地址:http://www.cnblogs.com/niuzaihenmang/p/5620915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!