Related Articles

Back to Latest Articles

How To Use Generic Lists In C# – Made Easy

Generic lists in C# are a data structures that allow us to add and remove objects to store inside without declaring its size.

Andraz Krzisnik
How To Use Generic Lists In C# – Made...

Generic lists allow us to store various different objects inside much like arrays or array lists. However, this type of list is something we call a strongly typed list. It also gives you more options with extension methods from System.Linq namespace.

Apart from that, the difference between array lists and generic lists is that generic list has a specified data type, while array list doesn’t.

In general, we want to use lists whenever we’re working with a larger data collection that varies in size through time of application use.

For example, if we use an array, we can only specify its size at the time we declare it. Therefore, we’d need to set a large size and just not use the free space in it down the road. However, this wouldn’t be really great for the long term, because it’s an unnecessary contraint.

In order to give our datasets space to grow we can just use lists, where we can increase or decrease their size whenever necessary.

Generic lists in C#

We’ll briefly go over the basic methods for using these lists. I’d like to recommend you to check out the post I made about array lists. Furthermore, the methods I used in that guide apply to this tutorial as well.

Now let’s go over the code examples and see what’s what.

List<double> nums = new List<double>();
nums.AddRange(new double[]{ 2.0, 5.5, -3.2});
Console.WriteLine(string.Join('|', nums));

Console.WriteLine(string.Join('|', nums));

Console.WriteLine("Min number in list: " + nums.Min());
Console.WriteLine("Max number in list: " + nums.Max());
Console.WriteLine("Average number of list: " + nums.Average());

As you can see, using extension methods is fairly straight forward. Furthermore, we can use these methods to do all sorts of things like sorting or checking all objects at once. In case you want to explore the functionality of these methods more in depth, I suggest you visit Microsofts official documentation.


I hope this short guide helped you gain a better understanding on using generic lists in C#. I also suggest you check out my other posts about data structures in C#.

In case you want to check out how it works in practice you can also download the demo project I set up and try it out yourself.

Related Articles

Region Splitting And Merging

How To Make Region Splitting And Merging Algorithm – C#

Region splitting and merging is a texture segmentation operation, where we use descriptors such as local mean intensity and standard deviation

Posted on by Andraz Krzisnik

How To Use Stacks In C# – Data Structures Made Easy

Stacks are limited access data structures, which means we can't access every element. It only allows us to access the last object we added.

Posted on by Andraz Krzisnik