0

我试图创建这样的扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;

namespace CommonLibs.CommonClasses.Extensions
{
    public static class EnumerableExt
    {
        public static IEnumerable<T> DistinctBy<T>(this IEnumerable<T> collection, Func<T, object> keyGroup)
        {
            return from x in collection group x by keyGroup into grp select grp.First();
        }
    }
}

但如果我想这样使用它:

public class PricingCoefficient
{
    public int Id { get; set; }
    public double FootageFrom { get; set; }
    public double? FootageTo { get; set; }
    public decimal? Coefficient { get; set; }
}

pricingCoefficients.DistinctBy(x => new { x.Coefficient, x.FootageFrom, x.FootageTo });

它给了我错误:

错误 30 类型“AnonymousType#1”不能用作泛型类型或方法“CommonLibs.CommonClasses.EnumerableExtensions.DistinctBy(System.Collections.Generic.IEnumerable, System.Func)”中的类型参数“TKey”。没有从“AnonymousType#1”到“System.IEquatable”的隐式引用转换。

知道如何使它成为扩展方法吗?

谢谢

4

2 回答 2

2

您需要另一种类型T2,一个类似的键选择器Func<T, T2> keyGroup并将其称为keyGroup(x)

public static IEnumerable<T> DistinctBy2<T,T2>(this IEnumerable<T> collection, Func<T, T2> keyGroup)
{
    return from x in collection group x by keyGroup(x) into grp select grp.First();
}
于 2013-09-20T06:59:59.773 回答
0

尝试这个:

public static IEnumerable<T> DistinctBy<T>(this IEnumerable<T> collection, 
                                           Func<T, object> keyGroup) {
    return from x in collection group x by keyGroup(x) into grp select grp.First();
}

注意:我无法重现您的问题,使用(keyGroup without(x)不会引发任何异常,产生. DistinctBy

于 2013-09-20T06:56:56.573 回答