如何在C#中的foreach循环中访问集合中的下一个值?

我正在使用C#并使用排序的List结构。 我正在尝试迭代List并且每次迭代我都想访问列表的下一个成员。 有没有办法做到这一点?

伪代码示例:

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

你不能。 使用a代替

 for(int i=0; i 

您可以保留以前的值:

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

使用带索引的常规for循环,并比较list [i]和list [i + 1]。 (但请确保仅循环到倒数第二个索引。)

或者,如果您真的想要使用foreach,您可以保留一个成员引用前一个成员并在下一次检查。 但我不推荐它。

如果有人如此倾向,你也可以为此编写一个Extension方法……

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

用法:

 List numList = new List { 1, 3, 5, 7, 9, 11, 13, 15 }; numList.ForEachNext((first, second) => { Console.WriteLine(string.Format("{0}, {1}", first, second)); }); 

LINQ可能是你的朋友。 这种方法适用于任何IEnumerable ,而不仅仅是IList 集合,如果您的集合永远不会结束或者在运行中以其他方式计算,这非常有用:

 class Program { static void Main(string[] args) { var list = new List { 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(); } }