Linq Distinct方法的扩展

来源:互联网 发布:java中main函数 编辑:程序博客网 时间:2024/04/25 08:00
MSDN给出的做法,具体参照:http://msdn.microsoft.com/zh-cn/library/bb338049.aspx

public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

使用方法如下(针对ID,和Name进行Distinct):

var query = people.DistinctBy(p => new { p.Id, p.Name });

若仅仅针对ID进行distinct:

var query = people.DistinctBy(p => p.Id);
0 0
原创粉丝点击