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