国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

為何Linq的Distinct實在是不給力

2020-01-24 03:20:50
字體:
供稿:網(wǎng)友
假設(shè)我們有一個類:Product

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
}
Main函數(shù)如下:
static void Main()
{
    List<Product> products = new List<Product>()
    {
        new Product(){ Id="1", Name="n1"},
        new Product(){ Id="1", Name="n2"},
        new Product(){ Id="2", Name="n1"},
        new Product(){ Id="2", Name="n2"},
    };
    var distinctProduct = products.Distinct();
    Console.ReadLine();
}
可以看到distinctProduct 的結(jié)果是:

image

因為Distinct 默認(rèn)比較的是Product對象的引用,所以返回4條數(shù)據(jù)。
那么如果我們希望返回Id唯一的product,那么該如何做呢?
 
Distinct方法還有另一個重載:
//通過使用指定的 System.Collections.Generic.IEqualityComparer<T> 對值進行比較
//返回序列中的非重復(fù)元素。
 public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source,
IEqualityComparer<TSource> comparer);
該重載接收一個IEqualityComparer的參數(shù)。
假設(shè)要按Id來篩選,那么應(yīng)該新建類ProductIdComparer 內(nèi)容如下:
public class ProductIdComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        if (x == null)
            return y == null;
        return x.Id == y.Id;
    }
    public int GetHashCode(Product obj)
    {
        if (obj == null)
            return 0;
        return obj.Id.GetHashCode();
    }
}
使用的時候,只需要
var distinctProduct = products.Distinct(new ProductIdComparer());
結(jié)果如下:

image

現(xiàn)在假設(shè)我們要 按照 Name來篩選重復(fù)呢?
很明顯,需要再添加一個類ProductNameComparer.
那能不能使用泛型類呢??
新建類PropertyComparer<T> 繼承IEqualityComparer<T> 內(nèi)容如下:
public class PropertyComparer<T> : IEqualityComparer<T>
{
    private PropertyInfo _PropertyInfo;
    /// <summary>
    /// 通過propertyName 獲取PropertyInfo對象   
    /// </summary>
    /// <param name="propertyName"></param>
    public PropertyComparer(string propertyName)
    {
        _PropertyInfo = typeof(T).GetProperty(propertyName,
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        if (_PropertyInfo == null)
        {
            throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                propertyName, typeof(T)));
        }
    }
    #region IEqualityComparer<T> Members
    public bool Equals(T x, T y)
    {
        object xValue = _PropertyInfo.GetValue(x, null);
        object yValue = _PropertyInfo.GetValue(y, null);
        if (xValue == null)
            return yValue == null;
        return xValue.Equals(yValue);
    }
    public int GetHashCode(T obj)
    {
        object propertyValue = _PropertyInfo.GetValue(obj, null);
        if (propertyValue == null)
            return 0;
        else
            return propertyValue.GetHashCode();
    }
    #endregion
}

主要是重寫的Equals 和GetHashCode 使用了屬性的值比較。
使用的時候,只需要:
//var distinctProduct = products.Distinct(new PropertyComparer<Product>("Id"));
var distinctProduct = products.Distinct(new PropertyComparer<Product>("Name"));

結(jié)果如下:

image

為什么微軟不提供PropertyEquality<T> 這個類呢?
按照上面的邏輯,這個類應(yīng)該沒有很復(fù)雜啊,細(xì)心的同學(xué)可以發(fā)現(xiàn)PropertyEquality 大量的使用了反射。每次獲取屬性的值的時候,都在調(diào)用
_PropertyInfo.GetValue(x, null);
可想而知,如果要篩選的記錄非常多的話,那么性能無疑會受到影響。
為了提升性能,可以使用表達式樹將反射調(diào)用改為委托調(diào)用,
具體代碼如下:

public class FastPropertyComparer<T> : IEqualityComparer<T>
{
    private Func<T, Object> getPropertyValueFunc = null;
    /// <summary>
    /// 通過propertyName 獲取PropertyInfo對象
    /// </summary>
    /// <param name="propertyName"></param>
    public FastPropertyComparer(string propertyName)
    {
        PropertyInfo _PropertyInfo = typeof(T).GetProperty(propertyName,
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        if (_PropertyInfo == null)
        {
            throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                propertyName, typeof(T)));
        }
        ParameterExpression expPara = Expression.Parameter(typeof(T), "obj");
        MemberExpression me = Expression.Property(expPara, _PropertyInfo);
        getPropertyValueFunc = Expression.Lambda<Func<T, object>>(me, expPara).Compile();
    }
    #region IEqualityComparer<T> Members
    public bool Equals(T x, T y)
    {
        object xValue = getPropertyValueFunc(x);
        object yValue = getPropertyValueFunc(y);
        if (xValue == null)
            return yValue == null;
        return xValue.Equals(yValue);
    }
    public int GetHashCode(T obj)
    {
        object propertyValue = getPropertyValueFunc(obj);
        if (propertyValue == null)
            return 0;
        else
            return propertyValue.GetHashCode();
    }
    #endregion
}

可以看到現(xiàn)在獲取值只需要getPropertyValueFunc(obj) 就可以了。
使用的時候:
var distinctProduct = products.Distinct(new FastPropertyComparer<Product>("Id")).ToList();
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 泸定县| 平塘县| 迁西县| 青川县| 黔西县| 滨海县| 泾川县| 新绛县| 随州市| 崇信县| 阜城县| 卢湾区| 湖口县| 武冈市| 大竹县| 上林县| 洞头县| 固安县| 紫云| 亚东县| 理塘县| 博兴县| 土默特右旗| 旬阳县| 蚌埠市| 曲松县| 高邮市| 永修县| 德安县| 常德市| 个旧市| 新平| 扎鲁特旗| 桃江县| 永泰县| 台北市| 沅江市| 日土县| 绥阳县| 宜黄县| 南通市|