C# Collection List

How to Read a C# List items in C#

List is a collection of items. We can use a foreach loop to loop through its items. The code snippet in Listing 6 reads all items of a List and displays on the console.

Foreach-loop. This is the best loop when no index is needed. We use the “foreach” keyword and declare a variable (like “prime” here) that is assigned to each element as we pass over it.

 

 

For-loop. Sometimes we want to access indexes of a List as we loop over its elements. A for-loop is ideal here. We print each element index with a string interpolation expression.

Tip: Arrays use Length. But Lists use Count. To loop backwards, start with list.Count – 1, and decrement to >= 0.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.