巧用 linq select 实现遍历集合返回元素 index
集合元素如下:
private List<string> dataSource = new List<string>() { "001", "002", "003", "004", "005" };
C# 代码,之前这样写:
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));
}