我很想知道如何修改现有的 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);
}
如果我想添加一个“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);
}