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