C#中的`foreach`循环是迭代集合的便捷方式,但它本身不提供当前迭代的索引。当您需要元素及其索引时,这可能会很不方便。本文探讨了在类似`foreach`的迭代中检索索引的两种有效方法。
目录
使用LINQ的Select()
方法
LINQ的Select()
方法提供了一种简洁的方法来获取元素及其索引。它将原始集合转换为一个新序列,其中每个元素与其索引配对。
using System;
using System.Collections.Generic;
using System.Linq;
public class ForeachIndexExample
{
public static void Main(string[] args)
{
List<string> names = new List<string>() { "Alice", "Bob", "Charlie", "David" };
// 使用Select()获取索引和元素
var indexedNames = names.Select((name, index) => new { Name = name, Index = index });
// 迭代索引序列
foreach (var item in indexedNames)
{
Console.WriteLine($"Name: {item.Name}, Index: {item.Index}");
}
}
}
此代码创建一个包含名称及其索引的新匿名类型。然后,`foreach`循环遍历此新序列,提供对这两条信息的访问。这种方法可读性好,适用于任何大小的集合。
使用标准for
循环
为了提高性能,特别是对于大型集合,标准的for
循环提供了一种更直接的方法。这避免了创建新序列的开销。
using System;
using System.Collections.Generic;
public class ForeachIndexExample
{
public static void Main(string[] args)
{
List<string> names = new List<string>() { "Alice", "Bob", "Charlie", "David" };
// 使用带有索引的for循环
for (int index = 0; index < names.Count; index++)
{
string name = names[index];
Console.WriteLine($"Name: {name}, Index: {index}");
}
}
}
此方法使用其索引直接访问元素。虽然它不使用`foreach`循环,但它为大型数据集提供了更有效的解决方案。
这两种方法的选择取决于您的优先级。Select()
方法提供了可读性,而for
循环为大型集合提供了更好的性能。在做出选择时,请考虑数据的规模和可读性的重要性。