【发布时间】:2016-04-06 03:32:18
【问题描述】:
在看到指定如何使用 Linq 枚举集合的索引的答案后,我决定编写一个扩展方法 WhereWithIndex,其行为类似于 Where,但输入函数应该有两个参数,项目和索引。
示例用法应该是:
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 来表示一般性following the official documentation,条件是一个谓词,所以我这么说。如何用 2 个参数表达委托的类型让我更加困惑,我尝试使用逗号分隔参数,但我只是猜测为 I could only fund examples of predicates with only one input。
它给了我错误:
Example.cs(22,29): error CS0246: The type or namespace name `T' could
not be found. Are you missing an assembly reference?
关于编写这种类型签名的任何想法?如果它在 C# 版本 6 中更简单,那么也可以提及它。
【问题讨论】:
-
顺便说一句,
Where的索引过载:msdn.microsoft.com/en-us/library/bb549418(v=vs.110).aspx;关于您的问题:制作一个通用方法:WhereWithIndex<T>如果您仍然需要它 -
您在方法名称后错过了
T:... WhereWithIndex<T>(...)。
标签: c# generics collections functional-programming extension-methods