我很想知道如何修改现有的LINQ函数以添加Func<T> TResult到函数签名,即允许它使用选择器(o => o.CustomField).
例如,在C#中,我可以.IsDistinct()用来检查整数列表是否不同.我还可以.IsDistinctBy(o => o.SomeField)用来检查字段o.SomeField中的整数是否不同.我相信,在幕后,.IsDistinctBy(...)有Func<T> TResult附加功能签名的东西吗?
我的问题是:获取现有LINQ扩展函数并将其转换为可以有参数的技术是(o => o.SomeField)什么?
这是一个例子.
此扩展函数检查列表是否单调增加(即值永远不会减少,如1,1,2,3,4,5,5):
main()
{
var MyList = new List<int>() {1,1,2,3,4,5,5};
DebugAssert(MyList.MyIsIncreasingMonotonically() == true);
}
public static bool MyIsIncreasingMonotonically<T>(this List<T> list) where T : IComparable
{
return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0).All(b => b);
}
Run Code Online (Sandbox Code Playgroud)
如果我想添加"By",我会添加一个参数Func<T> TResult.但是如何修改函数体以使其选择(o => o.SomeField)?
main()
{
DebugAssert(MyList.MyIsIncreasingMonotonicallyBy(o => o.CustomField) == true);
}
public static bool MyIsIncreasingMonotonicallyBy<T>(this List<T> list, Func<T> TResult) where T : IComparable
{
// Question: How do I modify this function to make it
// select by o => o.CustomField?
return list.Zip(list.Skip(1), (a, b) => a.CompareTo(b) <= 0).All(b => b);
}
Run Code Online (Sandbox Code Playgroud)
只需将 应用于Funca 和 b:
public static bool MyIsIncreasingMonotonicallyBy<T, TResult>(this IEnumerable<T> list, Func<T, TResult> selector)
where TResult : IComparable<TResult>
{
return list.Zip(list.Skip(1), (a, b) => selector(a).CompareTo(selector(b)) <= 0).All(b => b);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |