我试图创建这样的扩展方法:
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”的隐式引用转换。
知道如何使它成为扩展方法吗?
谢谢