我尝试创建这样的扩展方法:
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”类型不能用作类型参数 泛型或方法中的'TKey' “CommonLibs.CommonClasses.EnumerableExtensions.DistinctBy(System.Collections.Generic.IEnumerable, System.Func)”。没有隐式引用转换 'AnonymousType#1'到'System.IEquatable'。
知道如何将其作为扩展方法吗?
感谢
答案 0 :(得分: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();
}
答案 1 :(得分: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
重现您的问题(没有(x)
不会抛出任何异常,只是错误产生DistinctBy
的正确结果。