zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    模板语法
    django框架中登陆验证功能
    __call__
    JQuery基础
    JS中BOM和DOM操作
    Javascript基础
    css完结
    css深入
    css初识
    html深入解析
  • 原文地址:https://www.cnblogs.com/a849788087/p/7993545.html
Copyright © 2011-2022 走看看