首頁 > 後端開發 > C++ > 如何在 C# Foreach 迴圈中存取迭代索引?

如何在 C# Foreach 迴圈中存取迭代索引?

Mary-Kate Olsen
發布: 2025-01-27 17:56:10
原創
260 人瀏覽過

How Can I Access the Iteration Index in a C# Foreach Loop?

訪問 C# Foreach 循環中的迭代索引

C# foreach 循環提供了一種迭代集合的簡潔方法。 但是,本質上不支持直接訪問迭代索引。 以下是實現此目的的幾種方法:

1。手動計數器:

最簡單的方法涉及手動遞增計數器:

<code class="language-csharp">int index = 0;
foreach (var item in myCollection)
{
    // Use 'item' and 'index'
    index++;
}</code>
登入後複製

2。 LINQ 的 Select 與索引:

LINQ 的 Select 方法提供了包含索引的重載:

<code class="language-csharp">foreach (var item in myCollection.Select((value, index) => new { Value = value, Index = index }))
{
    var value = item.Value;
    var index = item.Index;
    // Use 'value' and 'index'
}</code>
登入後複製

這將創建一個包含值及其索引的匿名類型。

3。 ValueTuple(C# 7.0 及更高版本):

為了提高性能並避免堆分配(特別是對於大型集合),請使用 ValueTuple:

<code class="language-csharp">foreach (var (value, index) in myCollection.Select((value, index) => (value, index)))
{
    // Access 'value' and 'index' directly
}</code>
登入後複製

這利用元組解構來實現更清晰的語法。

4。 For 循環(替代):

對於需要索引訪問的情況,標準的 for 循環提供了更直接的解決方案:

<code class="language-csharp">for (int index = 0; index < myCollection.Count; index++)
{
    var item = myCollection[index];
    // Use 'item' and 'index'
}</code>
登入後複製

當索引對於循環邏輯至關重要時,通常首選此方法。 選擇最適合您的編碼風格和性能需求的方法。 對於簡單的情況,手動計數器就足夠了。 對於更大的集合或更複雜的場景,帶有 ValueTuple 的 LINQ 提供了可讀性和效率的平衡。 當索引操作是循環操作的核心時,for 循環仍然是一個可行的選項。

以上是如何在 C# Foreach 迴圈中存取迭代索引?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板