linq查询去重

通过自定义扩展方法DistinctBy实现去重

 

            

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;

        }

    }

}

        

方法的使用

1、针对ID,和Name进行Distinct

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

2、仅仅针对ID进行distinct:

var query = allProduct.DistinctBy(p => p.Id);
posted @ 2017-12-06 16:44  Cherry的冬天  阅读(432)  评论(0编辑  收藏  举报