Key Concepts

Review core concepts you need to learn to master this subject

Lists in C#

List<string> names = new List<string>(); List<Object> someObjects = new List<Object>();

In C#, a list is a generic data structure that can hold any type. Use the new operator and declare the element type in the angle brackets < >.

In the example code, names is a list containing string values. someObjects is a list containing Object instances.

Lists
Lesson 1 of 2
  1. 1
    At this point, we assume that you’re familiar with arrays: they’re useful tools for managing large amounts of sequential data. But arrays have their drawbacks: * They have a limited length * You…
  2. 2
    A list is a sequential data structure that can hold any type. Like arrays, you can use them to store any sequential information, like the letters of the alphabet, comments on a blogpost, the finish…
  3. 3
    Our first way to create lists and add items took multiple lines: List citiesList = new List (); citiesList.Add(“Delhi”); citiesList.Add(“Los Angeles”); We can do it all in one line using _objec…
  4. 4
    We can check on the status of our list in two ways. We can find the number of elements in the list using the Count property: List citiesList = new List { “Delhi”, “Los Angeles” }; int numberCiti…
  5. 5
    To remove a specific item from a list we use the Remove() method. It expects the specific item as an argument and it returns true if it was successfully removed. This code removes “Delhi” from the…
  6. 6
    If we need to remove all of the elements from a list, we could iterate through the entire list and call Remove(). The easier way is to use the Clear() method. List citiesList = new List { “Delh…
  7. 7
    Effectively, we can add an infinite number of items to a list: List numbers = new List (); for (int i = 0 ; i < 1000; i++) { numbers.Add(i); } We can access and edit them using bracket notati…
  8. 8
    So far we have added, accessed, and removed single elements in a list. What if we wanted to add, access, or remove multiple elements at once? In the world of lists we call a subsequence of elemen…
  9. 9
    Like arrays, we can perform an operation for every element in the list using for and foreach loops. With for loops, make sure to use Count to stay within the bounds of the list. for (int i = 0; i…
  10. 10
    You’ve done great with lists so far! It’s time to take a look at the bigger picture. Remember the one line we mentioned at the beginning of this lesson? using System.Collections.Generic; The lis…
  11. 11
    Well done! You’ve learned a lot of useful information in this lesson: * A list, or List , is a generic, sequential data structure. The specific type that it contains is specified upon instantiation…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo