我正在使用C#并使用一系列List<T>结构.我正在尝试遍历List每次迭代,我想访问列表的下一个成员.有没有办法做到这一点?
伪代码示例:
foreach (Member member in List)
{
    Compare(member, member.next);
}
mun*_*sor 58
你不能.使用a代替
for(int i=0; i<list.Count-1; i++)
   Compare(list[i], list[i+1]);
Mar*_*ell 19
您可以保留以前的值:
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,您可以保留对前一个成员的 Member 引用,并在下次检查。但我不会推荐它。
如果这样的话,您可能也可以为此编写一个扩展方法...
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));
});