在看到一个指定如何使用Linq枚举集合索引的答案之后,我决定编写一个扩展方法WhereWithIndex,它的行为类似于Where,但是输入函数应该有两个参数,即item和index。
示例用法应该是:
names = new String[] {"Bob", "Alice", "Luke", "Carol"}
names.WhereWithIndex( (_, index) => index % 2 == 0 ) // -> {"Bob", "Luke"}我已经能够将这个逻辑嵌入到我的程序中,看起来如下:
iterable
.Select((item, index) => new {item, index})
.Where(x => condition(item, index))
.Select(x => x.item);但是,我应该给这个扩展方法的类型签名仍然没有实现。我试过:
public static IEnumerable<T> WhereWithIndex(this IEnumerable<T> iterable, Predicate<T, int> condition) {因为我希望输入一个我不能用int或String标记它的可枚举的输入,所以我尝试使用T来表示通用性在正式文件之后,所以条件是一个谓词,所以我这么说了。如何表达带有两个参数的委托类型更让我无法理解,我试着用逗号分隔参数,但我只是猜测为我只能用一个输入来为谓词示例提供资金。。
它给了我一个错误:
Example.cs(22,29): error CS0246: The type or namespace name `T' could
not be found. Are you missing an assembly reference?对写这种签名有什么想法吗?如果在C#版本6中它更简单,那么也很高兴提到它。
发布于 2016-01-01 18:14:35
这里有一个已存在版本的Where可以做到这一点。它有这样的签名:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);您唯一缺少的签名是<TSource>旁边的Where。这告诉编译器函数是泛型的。加上使用Func<TSource, int, bool>而不是Predicate<T, int>。在C#中,Func<P1, P2, P3, R>是一个接受P1、P2、P3并返回R的函数,如:
public R MyFunction(P1 p1, P2 p2, P3 p3) { ... }另一方面,Action<P1, P2>是一个接受P1和P2而不返回任何内容的函数:
public void MyAction(P1 p1, P2 p2) { ... }注意,在这些示例中,MyFunction和MyAction不是泛型(P1..P3和R需要是实际类型)。如果您想使它成为通用的,您可以将其更改为:
public void MyAction<P1, P2>(P1 p1, P2 p2) { ... }在这种情况下,P1和P2是任意类型的变量名。
https://stackoverflow.com/questions/34558653
复制相似问题