Beginner’s Guide To C# List Class

Have you ever ever been working with an array and all of it will get out of hand?
You begin with a easy assortment, then notice it’s worthwhile to add extra objects, take away a couple of, perhaps kind them, and instantly arrays really feel clunky.
The excellent news is there is a answer and that’s the place C# Lists are available. They take away a lot of the ache that comes with arrays, letting you give attention to fixing issues as an alternative of wrestling with syntax.
The trick, after all, is figuring out use them correctly. So on this information, I’ll stroll you thru every little thing it’s worthwhile to know to make use of Lists confidently, from creating one to constructing a easy venture round them, and avoiding the frequent errors.
Sidenote: Wish to study extra about C#? Check out my complete C# / .NET course!
It’s the one course it’s worthwhile to study C# programming and grasp the .NET platform and Blazor. You’ll study every little thing from scratch and put your abilities to the take a look at with workouts, quizzes, and tasks!
With that out of the best way, let’s get into this 5-minute tutorial.
What’s the Checklist class and what does it do?
If you first begin working in C#, arrays normally really feel like the plain alternative for holding a number of values of the identical sort. Primarily as a result of they’re easy and so they work.
The factor is arrays have a catch in that after you determine what number of components they’ll maintain, that’s it. You’ll be able to’t simply add extra later with out making a model new array and copying every little thing over. As you’ll be able to think about, this is usually a ache to take care of.
That is the place the Checklist
A Checklist
It’s virtually like an array is a chunk of A4 paper. When you run out of area, you’re caught. However a Checklist is extra like a Google Doc. It might develop as you retain typing or shrink if you delete issues, with out you doing something further.
Make sense?
One other necessary element to know is the
Which means in case you make a Checklist
It looks as if a limitation, however it’s truly good sort security. It additionally retains your code clear, executes quick, and prevents messy bugs.
The fundamental Checklist syntax
So now that we perceive what this function is, let’s check out it in code.
Here is the essential syntax:
utilizing System;
utilizing System.Collections.Generic;
class Program
{
static void Foremost()
{
// A listing of strings
Checklist names = new Checklist();
// A listing of integers
Checklist numbers = new Checklist();
}
}
What’s occurring right here is fairly easy. We’re telling C# we wish a listing, and we’re additionally telling it what sort of knowledge that record ought to maintain. Proper now, each lists are empty, however able to be stuffed.
And the simplest technique to actually perceive how they work is to make use of them in an precise instance, so let’s try this subsequent.
The way to use the Checklist class in C#
We’re going to construct a easy to-do record program.
It is a excellent instance as a result of duties aren’t fastened. You add new ones, cross off outdated ones, and typically examine what’s left. That type of flexibility is supplied by Lists and is way more advanced to implement utilizing arrays.
For instance
If we tried to do that with an array, we’d hit a wall rapidly, as a result of arrays drive you to choose a measurement up entrance.
So let’s say you create one for five duties, however tomorrow you instantly have 6. Now you’d need to create a brand-new array and duplicate every little thing over. However with a Checklist, that downside disappears. You’ll be able to simply maintain including, and it’ll deal with the resizing for you.
Make sense?
So let’s get into creating this.
The way to create a Checklist
Let’s begin by making an empty Checklist to carry our duties:
utilizing System;
utilizing System.Collections.Generic;
class Program
{
static void Foremost()
{
// Create a brand new record of duties
Checklist duties = new Checklist();
}
}
We’ve set this to strings as a result of we’re solely going to make use of textual content values like “Purchase groceries” or “Name mother.”
Bear in mind, although, in case you tried so as to add a quantity or the rest, the compiler would cease you earlier than you even run this system. So be sure you select the proper sort that you simply need to use first!
Proper now, our record is empty, however it’s prepared to carry any string we need to add, so we’ll do that utilizing Add().
The way to add objects to your Checklist
So let’s add some duties utilizing Add()
duties.Add("Purchase groceries");
duties.Add("End C# venture");
duties.Add("Name mother");
Each time you name Add(), C# takes the brand new merchandise and sticks it on the finish of the record. That’s all you must do and there’s no worrying about working out of area or shifting issues round.
The sweetness right here is flexibility. You could possibly add 3 duties immediately, 10 tomorrow, and none the following day. The Checklist simply grows or shrinks as you want it to.
So now that we’ve got our record, we want to have the ability to do issues with the objects on it.
The way to entry objects in your Checklist
There are occasions if you gained’t need the entire record, however just one particular merchandise.
For instance
Possibly you simply need to see the primary merchandise on the prime of the record so you will get it accomplished and ignore the remaining for now.
We are able to try this like so:
Console.WriteLine(duties[0]); // Output: Purchase groceries
So what’s occurring right here?
Should you don’t know, lists set up their objects utilizing an index. Nonetheless, the primary merchandise is at index begins at 0, the second at index 1, and so forth.
By writing duties[0], we’re saying, “present me the merchandise at place 0,” and C# provides us again “Purchase groceries”.
The way to iterate by way of your Checklist
Accessing one merchandise is helpful when you recognize precisely which one you need, similar to checking simply the primary activity so you recognize the place to begin. However what if you wish to see all of the duties in your record?
Effectively, you could possibly do that by printing every index one after the other:
Console.WriteLine(duties[0]);
Console.WriteLine(duties[1]);
Console.WriteLine(duties[2]);
That works for 3 objects, however what in case you had 30? Or 300? Writing all these traces could be a nightmare.
That’s the place loops are available.
A foreach loop will robotically stroll by way of each merchandise in your record, irrespective of what number of there are:
foreach (string activity in duties)
{
Console.WriteLine(activity);
}
This prints every activity so as, one after the opposite. Add extra duties, take away some, shuffle them round and it doesn’t matter. The loop at all times adjusts to no matter is within the record at that second.
Trace:
We are able to use the foreach assertion for each sort implementing the IEnumerable or IEnumerable
Talking of eradicating objects…
The way to take away objects out of your Checklist
When you’ve completed a activity, you don’t really need it sitting in your record anymore. That’s the place Take away() and RemoveAt() are available.
For instance
If you recognize the identify of the merchandise you need to filter out, you’ll be able to take away it by worth with Take away():
duties.Take away("Name mother");
It will look by way of the record, discover “Name mother,” and take it out.
Let’s be sincere, although. Although that is only a fundamental to-do record app, you in all probability nonetheless do not need to have to jot down the merchandise every time you need to delete it as a result of that is further work.
It’s extra seemingly, you’d need to take away one thing at a sure place. That’s what RemoveAt() is for.
For instance
To illustrate that you simply simply completed the very first thing in your record, you could possibly then set it to take away that first merchandise and ‘tick it off’.
duties.RemoveAt(0); // removes "Purchase groceries"
This then removes our prime merchandise, which on this case was our grocery buying.
Higher nonetheless?
After eradicating, the Checklist robotically closes the hole so that you don’t find yourself with empty areas. All the pieces shifts down, holding the record good and tidy.
The way to learn the way many objects are in your record
Generally it’s not in regards to the objects themselves, however about figuring out what number of you’ve obtained left to take care of. That’s what the Rely property is for.
For instance
Say you’ve been chipping away at your to-do record and also you simply need a fast reminder of what number of duties are nonetheless sitting there. Effectively, as an alternative of going by way of the record one after the other, Rely tells you immediately:
Console.WriteLine("You have got " + duties.Rely + " duties left.");
In case your record presently has 3 objects, Rely will return 3. Cross one off with Take away() or RemoveAt(), and Rely robotically drops to 2.
Why is this handy?
As a result of in actual applications, you’ll usually need to give customers suggestions and even make choices based mostly on what number of objects are in a listing.
For instance
You could possibly:
-
Warn the person when their buying cart is empty
-
Present a message when a to-do record is all completed
-
Restrict the variety of gamers who can be a part of a recreation foyer
And the most effective half is you don’t need to manually maintain observe of this quantity your self. The Checklist does all of the bookkeeping within the background and simply arms you the end result.
Helpful, proper?
Storing customized objects in Lists
Moreover utilizing easy sorts, similar to string or int, we are able to additionally use our customized objects and retailer them in a Checklist
For instance
Let’s say we’ve got a fancy sort, similar to a Particular person class, we are able to create a Checklist to retailer all the staff engaged on a venture:
var staff = new Checklist();
staff.Add(new Particular person("John", "Doe"));
On this easy instance, the Particular person class has first and final identify properties that we are able to set within the sort’s constructor. We create an object and add it to the record.
Different record choices
By now, you recognize the on a regular basis belongings you’ll do with a Checklist: including, eradicating, checking objects, and looping by way of them. That stuff is the bread and butter and what you’ll use most days.
Nonetheless, the Checklist class truly comes with an entire toolbox of additional strategies that you may pull out if you want them. Consider these like shortcuts: you gained’t use them always, however when the scenario arises, they will prevent time and make your code rather a lot cleaner.
Let’s undergo a couple of of essentially the most helpful ones.
The way to examine if one thing is already in your record
Generally you’ll need to know if an merchandise is already on the record earlier than you add it. In any other case, you may find yourself with duplicates you didn’t imply to have. That’s what the Incorporates() methodology is for.
For instance
Let’s say our record is a buying record and we need to examine if “Milk” is already there earlier than including it once more.
We may try this like this:
if (duties.Incorporates("Milk"))
{
Console.WriteLine("Milk is already on the record!");
}
else
{
duties.Add("Milk");
Console.WriteLine("Milk added to the record.");
}
Easy sufficient, proper?
What’s cool is you don’t need to hard-code this for each doable merchandise as a result of Incorporates() checks no matter worth you go in.
So in case you requested about “Eggs,” it might look by way of the record for “Eggs” and reply accordingly:
-
If “Eggs” is there, you’ll see “Eggs are already on the record!”
-
If “Eggs” isn’t there, it will get added, and also you’ll see “Eggs added to the record”
This makes your program versatile as a result of the identical logic works for any merchandise the person sorts in.
Trace:
If uniqueness is crucial in your use case, think about using a HashSet
The way to discover the place of an merchandise in your record
Generally it’s not sufficient to know if one thing is in your record. Generally you additionally need to know the place it’s. That’s what the IndexOf() methodology is for.
Consider it as a search software that tells you the place of an merchandise.
For instance
Let’s say we need to discover “Milk” in our buying record:
int index = duties.IndexOf("Milk");
if (index != -1)
{
Console.WriteLine($"Milk is at place {index} within the record.");
}
else
{
Console.WriteLine("Milk will not be on the record.");
}
If “Milk” is discovered, IndexOf() provides you its index (bear in mind, lists begin at 0). If it’s not discovered, it returns -1.
Why does this matter?
As a result of as soon as you recognize the place one thing is, you are able to do extra with it.
You may:
-
Exchange “Milk” with another choice. Maybe we swap it for “Oat Milk”
-
Or if it wasn’t a buying record, perhaps we would need to spotlight it in a UI by pointing to that place
-
And even queue up the following merchandise after it (suppose songs in a playlist).
IndexOf() is much less about simply printing the place one thing is and extra about providing you with the place so you’ll be able to act on it nevertheless you want.
The way to set up your record with Type() and Reverse()
Thus far, we’ve been working with objects separately, however typically you’ll need to set up the entire record. Two strategies that assist with this are Type() and Reverse(). So let’s check out every of them.
Type() arranges every little thing in ascending order. Which means it types textual content alphabetically, or for numbers it types by smallest to largest.
For instance
If we’ve got our present buying record from earlier, we are able to alphabetize it like so:
Checklist duties = new Checklist
{
"Stroll the canine",
"Purchase groceries",
"Name mother"
};
duties.Type();
foreach (string activity in duties)
{
Console.WriteLine(activity);
}
This may then output:
Purchase groceries
Name mother
Stroll the canine
Good and neat.
We are able to additionally use Reverse() to flip the present order of the record.
For instance
Let’s say that you’ve a online game, and also you need to rank the very best scores from largest to smallest. With Type(), it might rank them from lowest to smallest.
However Reverse() would set up it, however then flip that so we see the most important quantity and thus the very best rating on the prime.
Checklist scores = new Checklist { 50, 200, 120, 80 };
// Type from lowest to highest
scores.Type();
// Reverse so the very best scores are first
scores.Reverse();
foreach (int rating in scores)
{
Console.WriteLine(rating);
}
This then provides the very best rating:
The way to insert an merchandise at a particular place in your record
Thus far, we’ve been including objects to the tip of a listing with Add(), however typically, the order actually issues, and also you’ll need to put one thing on the prime or proper within the center as an alternative of the tip.
That’s what Insert() is for.
For instance
Let’s say you’re constructing a to-do record and instantly bear in mind one thing pressing, like paying a invoice comes up, and so it’s worthwhile to prioritize this on the prime of the record in the beginning else.
We may try this like so:
Checklist duties = new Checklist
{
"Purchase groceries",
"Name mother",
"Stroll the canine"
};
// Insert pressing activity on the very prime (index 0)
duties.Insert(0, "Pay electrical energy invoice ASAP");
foreach (string activity in duties)
{
Console.WriteLine(activity);
}
Output:
Pay electrical energy invoice ASAP
Purchase groceries
Name mother
Stroll the canine
By giving Insert() an index (on this case 0) and a price, you inform the record precisely the place the brand new merchandise ought to go.
Additionally, every little thing else shifts down robotically, so nothing will get overwritten.
The way to clear your record
Generally, you don’t simply need to take away one or two objects. Maybe you need to wipe the slate clear and begin recent. That’s what the Clear() methodology does.
Consider it like erasing a whiteboard. All the pieces that was on there may be gone, and also you’re left with a very empty record that’s prepared for use once more.
For instance
Checklist duties = new Checklist
{
"Purchase groceries",
"Name mother",
"Stroll the canine"
};
duties.Clear();
Console.WriteLine("Duties left: " + duties.Rely);
It will then clear the entire record and allow you to comprehend it’s empty like so:
That is particularly helpful if you’re reusing the identical record in a program however don’t need to create a model new one each time.
Maybe you probably did all Monday’s duties and now you need to fill this out for Tuesday and so on.
Time to present Checklist a attempt in your personal code!
As you’ll be able to see, Checklists take the stress out of managing information in C#. As a substitute of worrying about array sizes, you’ll be able to give attention to the precise downside you’re fixing.
One of the simplest ways to essentially perceive them is to mess around with them!
So why not attempt constructing your personal mini to-do record app, experiment with including and eradicating objects, or take a look at out Type() and Reverse() on a listing of numbers. The extra you apply, the extra pure Lists will really feel.
Hearth up your editor, write some code, and see what you’ll be able to construct.
P.S.
Don’t neglect. If you wish to study extra about C# and the .NET platform, then check out my complete course:
It’s the one course it’s worthwhile to study C# programming and grasp the .NET platform. You’ll study every little thing from scratch and put your abilities to the take a look at with workouts, quizzes, and tasks!
Plus, when you be a part of, you may have the chance to from me, different college students and dealing tech professionals.
Greatest articles. Greatest assets. Just for ZTM subscribers.
Should you loved this submit and need to get extra prefer it sooner or later, subscribe under. By becoming a member of the ZTM group of over 100,000 builders you’ll obtain Net Developer Month-to-month (the quickest rising month-to-month publication for builders) and different unique ZTM posts, alternatives and gives.
No spam ever, unsubscribe anytime
Wish to learn extra articles on C#?
Try all of my different guides under:


