在C#中使用foreach循環的時候我們有時會碰到需要索引的情況,在for循環中我們可以得到循環索引 , foreach并不直接提供 , 下面介紹4種foreach獲取索引的方法,希望對大家有用處:在循環外部聲明 index 變量,每次循環時手動遞增:int index = 0;
foreach (var item in collection)
{
Console.WriteLine($"{index}: {item}");
index++;
}
通過 Select 方法將元素與索引綁定為元組,結合 C# 7.0+ 的元組解構語法:foreach (var (item, index) in collection.Select((value, i) => (value, i)))
{
Console.WriteLine($"{index}: {item}");
}
- 需注意 System.Linq 命名空間和 System.ValueTuple 包(舊版本需手動安裝)?。
自定義擴展方法 WithIndex,增強代碼復用性:public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
return source.Select((item, index) => (item, index));
}
foreach (var (item, index) in collection.WithIndex())
{
Console.WriteLine($"{index}: {item}");
}
調用集合的 IndexOf 方法直接獲取元素索引(適用于 List<T> 等支持索引查找的集合):foreach (var item in collection)
{
int index = collection.IndexOf(item);
Console.WriteLine($"{index}: {item}");
}
- 依賴集合的 IndexOf 實現,僅適用于元素唯一且支持索引查找的集合?。
- 性能較差?:每次循環均遍歷集合查找索引,時間復雜度為 O(n^2)?。
- LINQ 方法?:引入輕微性能開銷(如迭代器生成),但對大多數場景影響可忽略?。
- 擴展方法?:適合高頻使用場景,平衡性能與代碼整潔度?。
- IndexOf:元素唯一且需動態查找索引,性能差,重復元素不可靠?。
選擇時需根據具體需求(如代碼簡潔性、性能要求、框架版本兼容性)綜合考量。
該文章在 2025/3/6 11:13:39 編輯過