【C# 代码小技巧】巧用 linq select 实现遍历集合返回元素 index
background
要求: 将 list 集合中的元素遍历输出的时候, 顺便输出其 index.
集合元素如下:
private List<string> dataSource = new List<string>() { "001", "002", "003", "004", "005" };
c# 代码实现
以前我可能会这写, 感觉很low:
public void Run_v1()
{
var index = 0;
foreach (var item in dataSource)
{
index++;
Console.WriteLine($"{index}. {item}");
}
}
使用 linq 的改进写法:
public void Run_v2()
{
var items = dataSource.Select((item, i) => $"{i + 1}. {item}").ToList();
items.ForEach(i => Console.WriteLine(i));
}
select 源码
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
return SelectIterator(source, selector);
}
private static IEnumerable<TResult> SelectIterator<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
{
int index = -1;
foreach (TSource item in source)
{
index = checked(index + 1);
yield return selector(item, index);
}
}
reference
感谢: