Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a List<int> with [0,4,6,8,9,11,14...] and I would like to always get two consecutive values ​​in a loop. For example, the value 0;4 then 4;6 followed by 6;8 and so on until the end.

What I have tried:

Does anyone know how to write it, for example, for a For cycle? Or any other cycle?
Thank you in advance for your reply

David
Posted
Updated 29-Nov-22 22:51pm

Try this:
C#
List<int> list = new List<int> { 0, 4, 6, 8, 9, 11, 14 };
for (int index = 0; index < list.Count - 1; index++)
    {
    Console.WriteLine($"{list[index]}, {list[index + 1]}");
    }
}
 
Share this answer
 
Comments
dejf111 30-Nov-22 5:06am    
That's exactly it. Thank you.
OriginalGriff 30-Nov-22 6:38am    
You're welcome!
The loop is quite straightforward. You start from index zero and take two values. You then increment the index value and check that it does not point to the very last entry. If it does then there is only one number left, if it does not, then you have at least two still left. So repeat the above until you find the last entry, or there are no more items in the list.
C#
for (int i = 0; i < list.Count; ++i)
{
    if (i == list.Count - 1) // the last item
        break;
    // list[i] and list[i + 1] are the next two items
}


OriginalGriff's solution above is even more straightforward.
 
Share this answer
 
v2
Comments
Richard Deeming 30-Nov-22 5:11am    
I prefer Griff's solution - modifying the end-point of the loop, rather than adding a test-and-break within the loop. :)
Richard MacCutchan 30-Nov-22 5:13am    
My sample caters for an odd number of entries.
Richard Deeming 30-Nov-22 5:14am    
So does solution 1. :)
Richard MacCutchan 30-Nov-22 5:15am    
Ha ha, of course it does. :(

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