Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of items, how can I select two consecutive items each time, for example (1 and 2) (2 and 3) (3 and 4)...etc?

What I have tried:

for (i = 0; i <= list.Count-1; i++)
           {
               //var first = list(i);
               //var second = list(i+1);

           }
Posted
Updated 23-Jan-18 4:27am
Comments
johannesnestler 23-Jan-18 10:22am    
so what's the Problem? You talking about selection so the question maybe has to do with a UI-component/Control Problem because a "list" itself has no selection feature. So please try to formulate a better question and explain your real problem...

1 solution

Assuming the source implements IList<T> or IReadOnlyList<T>:
C#
for (int i = 0; i < list.Count - 1; i++)
{
    var first = list[i];
    var second = list[i + 1];
}

If you want to use LINQ:
C#
foreach (var pair in list.Zip(list.Skip(1), (first, second) => (first, second)))
{
    var first = pair.first;
    var second = pair.second;
}
(Using the new C# 7 value tuple syntax[^]. If you're using an older compiler, or targeting an older framework, use an anonymous type instead.)
 
Share this answer
 
Comments
Mazin78 23-Jan-18 16:31pm    
Thank you, it gives me what I need.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900