Home
C# List Absolute Basics
Blog Date 18th May 2021
The Code
List<string> MyList = new List<string>();
List<string> Mylist = new List<string> { "David", "Julie" };
Mylist.Add("Ren");
Mylist.Add("Sharon");
Mylist.Add("John");
Mylist.Add("Sarah");
Mylist.Insert(0, "Alan");
Mylist.Remove("Ren");
Mylist.RemoveAt(2);
Mylist.IndexOf("Ren");
Mylist.Sort();
The Explanation
There's always more than one way to do something in C# and "List" is no exception. Declaring (creating, making, initialising...)a list has at least 2 options.
List<string> MyList = new List<string>();
This is my usual choice. Here we just create it ready to mess with it later.
List<string> Mylist = new List<string> { "David", "Julie" };
This time we are creating the list with items for the list directly.
Mylist.Add("Ren");
Here we add an item to the list. This works however the list was created. It's worth noting the added item is added to the END of the list. If you want to position a new item in a specific place...
Mylist.Insert(2, "Alan");
This will insert "Alan" into the list at position 2 - REMEMBER we start counting from 0 (zero) so in real terms this would be the 3rd position.
Mylist.Remove("Ren");
This will remove THE FIRST ENTRY of the matching string. So if the word "Ren" is in the list 3 times only the first "Ren" is removed.
Mylist.RemoveAt(2);
This removes whatever is in the numerical position, in this case position 2. Again REMEMBER we start counting from 0 (zero).
Mylist.IndexOf("Ren");
This returns the position, index of the string in the brackets. Again worth noting it finds the FIRST example, so it there is a "Ren" in postions 1 and 4 this will return a 1. If nothing is found, ie there is no match, then it returns -1.
Mylist.Sort();
This sorts the list, the default being alphanumerically. There are many many many more complex ways of sorting lists, that's for another day.
'ere, gis a job, I can do that... contact ren@techsolus.co.uk
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home