簡體   English   中英

如何在C#中的foreach循環中訪問集合中的下一個值?

[英]How can I access the next value in a collection inside a foreach loop in C#?

我正在使用C#並使用排序的List<T>結構。 我正在嘗試迭代List並且每次迭代我都想訪問列表的下一個成員。 有沒有辦法做到這一點?

偽代碼示例:

foreach (Member member in List)
{
    Compare(member, member.next);
}

你不能。 使用a代替

for(int i=0; i<list.Count-1; i++)
   Compare(list[i], list[i+1]);

您可以保留以前的值:

T prev = default(T);
bool first = true;
foreach(T item in list) {
    if(first) {
        first = false;
    } else {
        Compare(prev, item);
    }
    prev = item;
}

如果有人如此傾向,你也可以為此編寫一個擴展方法......

public static void ForEachNext<T>(this IList<T> collection, Action<T, T> func)
{
    for (int i = 0; i < collection.Count - 1; i++)
        func(collection[i], collection[i + 1]);
}

用法:

List<int> numList = new List<int> { 1, 3, 5, 7, 9, 11, 13, 15 };

numList.ForEachNext((first, second) => 
{
    Console.WriteLine(string.Format("{0}, {1}", first, second));
});

使用帶索引的常規for循環,並比較list [i]和list [i + 1]。 (但請確保僅循環到倒數第二個索引。)

或者,如果您真的想使用foreach,您可以保留一個成員引用前一個成員並在下一次檢查。 但我不推薦它。

LINQ可能是你的朋友。 這種方法適用於任何IEnumerable <T>,而不僅僅是IList <T>集合,如果您的集合永遠不會結束或者在運行中進行其他計算,這種方法非常有用:

class Program {
    static void Main(string[] args) {
        var list = new List<Int32> { 1, 2, 3, 4, 5 };
        foreach (var comparison in list.Zip(list.Skip(1), Compare)) {
            Console.WriteLine(comparison);
        }
        Console.ReadKey();
    }

    static Int32 Compare(Int32 first, Int32 second) {
        return first - second;
    }
}
XmlNode root = xdoc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("descendant::create-backup-sets/new-file-system-backup-set");

for (int j = 0; j < nodeList.Count; j++ )
{                
    for (int i = 0; i <= nodeList.Item(j).ChildNodes.Count - 1; i++)
    {
        if (nodeList.Item(j).ChildNodes[i].Name == "basic-set-info")
        {
            if (nodeList.Item(j).ChildNodes[i].Attributes["name"].Value != null)
            {
                // retrieve backup name
                _bName = nodeList.Item(j).ChildNodes[i].Attributes["name"].Value.ToString();
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM