一、手動維護索引變量
?實現方式?:
在循環外部聲明索引變量,每次迭代手動遞增:
int index = 0; foreach (var item in collection) { Console.WriteLine($"{index}: {item}"); index++; }
?特點?:
- 簡單直接,無需引入額外依賴12。
- 需注意線程安全及變量作用域問題。
二、LINQ?Select
?+ 元組解構
?實現方式?:
利用 LINQ 的?Select
?方法將元素與索引綁定為元組(C# 7.0+ 支持元組解構語法):
foreach (var (item, index) in collection.Select((value, i) => (value, i))) { Console.WriteLine($"{index}: {item}"); }
?特點?:
- 代碼簡潔,避免手動維護索引13。
- 需引入?
System.Linq
?命名空間。
三、擴展方法封裝索引
?實現方式?:
自定義擴展方法?WithIndex
,將集合元素與索引打包返回:
public static class EnumerableExtensions { 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}"); }
?特點?:
- 增強代碼復用性,適用于頻繁獲取索引的場景3。
四、使用?for
?循環替代
?實現方式?:
若需直接操作索引,可改用?for
?循環:
for (int i = 0; i < collection.Count; i++) { var item = collection[i]; Console.WriteLine($"{i}: {item}"); }
?特點?:
- 直接訪問索引,適用于支持索引器的集合(如數組、
List<T>
)57。 - 無法用于不支持索引器的集合(如?
IEnumerable<T>
)。
方法對比與適用場景
?方法? | ?適用場景? | ?優點? | ?限制? |
---|---|---|---|
手動維護索引變量 | 簡單場景,無需復雜依賴 | 無額外依賴,靈活 | 需手動管理,易出錯 |
LINQ + 元組解構 | 需要簡潔語法且支持 C# 7.0+ 的項目 | 代碼緊湊 | 依賴 LINQ,性能略低 |
擴展方法 | 高復用性需求 | 可復用,代碼結構清晰 | 需預先定義擴展類 |
for ?循環替代 | 支持索引器的集合(數組、List<T> 等) | 直接高效 | 不適用于?IEnumerable<T> |
?操作建議?:
- 優先選擇 ?LINQ + 元組解構? 或 ?擴展方法?,以保持代碼簡潔性和可維護性13。
- 對性能敏感的場景,改用?
for
?循環或手動維護索引57。