我有一个 ForEachWithIndex EM
static void ForEachWithIndex<T>(this IEnumerable<T> enu, Action<T, int> action)
{
int i = 0;
foreach(T item in enu)
action(item, i++);
}
我是这样调用它的
my_int_array.ForEachWithIndex((x, i) => x += i);
现在我想创建一个检查条件然后执行该操作的程序。
通常我用上面的作为
my_int_array.ForEachWithIndex((x,i) =>
{
if (x != 0)
x += i;
});
我想要一个将那个条件也作为参数的 EM。如何做到这一点?
请您参考如下方法:
我会尽量避免构建一个包罗万象的大型扩展方法。打破它,就像 LINQ 一样。
不过,就我个人而言,我实际上不会任何 - 我会使用 LINQ 构建查询,然后使用 foreach 语句来执行操作:
// Assuming you want the *original* indexes
var query = array.Select((Value, Index) => new { value, Index })
.Where(pair => pair.Index != 0);
foreach (var pair in query)
{
// Do something
}
很难确切知道您要做什么,因为增加 lambda 参数不会真正实现任何目标。不过,我会强烈鼓励您考虑组合 block ...您可能会发现 Eric Lippert's views on foreach vs ForEach有趣。
