zoukankan      html  css  js  c++  java
  • linq Distinct 去除重复数据

    转载:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html

    只可惜linq默认不支持.Distinct(p => p.ID);

    试想如果能写成下面的样子,是不是更简单优雅:

    var p1 = products.Distinct(p => p.ID);
    var p2 = products.Distinct(p => p.Name);
    

     使用一个简单的 lambda 作为参数,也符合 Linq 一贯的风格。

    扩展方法:

    public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector,
        IEqualityComparer<V> comparer = EqualityComparer<V>.Default)
    {
        return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer));
    }
    using System;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;
    using System.Linq;
    
    public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;
        private IEqualityComparer<V> comparer;
    
        public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer)
        {
            this.keySelector = keySelector;
            this.comparer = comparer;
        }
    
        public CommonEqualityComparer(Func<T, V> keySelector)
            : this(keySelector, EqualityComparer<V>.Default)
        {  }
    
        public bool Equals(T x, T y)
        {
            return comparer.Equals(keySelector(x), keySelector(y));
        }
    
        public int GetHashCode(T obj)
        {
            return comparer.GetHashCode(keySelector(obj));
        }
    }
  • 相关阅读:
    javascript执行上下文
    javascript深浅拷贝
    javascript模块化
    javascript类型转换
    闭包
    通过插槽分发内容
    组件上使用v-model
    Vue $emit $event 传值(子to父)
    Vue Prop属性(父to子)
    Vue组件全局/局部注册
  • 原文地址:https://www.cnblogs.com/51net/p/4435719.html
Copyright © 2011-2022 走看看