【发布时间】:2019-09-24 05:58:33
【问题描述】:
IEnumerable 的重载之一是:
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);
我希望在选择器中包含源代码。我知道这听起来违反直觉,因为您首先提供了 Select 的源代码,但 JavaScript 也有类似的东西。我想在这里快速使用它:
var greetings = new List<string> { "John", "Keith", "Sarah", "Matt" }.Select((name, index, source) => {
if (name == source.First())
return $"{name} (Todays Winner)";
return name;
});
上面会报错,因为Select的selector参数没有返回3个值。只是当前对象和索引。我希望它包含源代码。
我不想先单独创建列表,然后对它执行 .first。
这是我在扩展方面的进展;我不确定如何实现它。
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult, IEnumerable<TSource>> selector)
{
//not sure what to put in here, must be missing something simple ;(
}
更新
上述情况只是一个虚构的例子。我的实际情况需要使用.Last() 而不是.First(),所以索引不会有用,因为我们不知道最后一个索引是什么,而不是第一个索引是零。因此我需要将源传回。
【问题讨论】:
标签: c# linq select ienumerable class-extensions