Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use C# List Class



List < T > Class

The Collection classes are a group of classes designed specifically for grouping together objects and performing tasks on them. List class is a collection and defined in the System.Collections.Generic namespace and it provides the methods and properties like other Collection classes such as add, insert, remove, search etc. It’s the replacement for arrays, linked lists, queues, and most other one-dimensional data structures. This is because it has all kinds of extra functionality, including the ability to grow in size on-demand.

The C# List < T > class represents a strongly typed list of objects that can be accessed by index and it supports storing values of a specific type without casting to or from the object.

List < T >

The parameter T is the type of elements in the List.

Add elements in List collection

Add Integer values in the List collection

List<int> iList = new List<int>();
iList.Add(2);
iList.Add(3);
iList.Add(5);
iList.Add(7);

Add String values in the List

List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

Count list elements

How to find the size of a list?

You can use count property to know the number of items in the List collection or the length of a C# List

colors.Count

Retrieve List elements

You can retrieve items from List collection by using for loops.

foreach loop

foreach (string color in colors)
{
    MessageBox.Show(color);
}

for loop

 
for (int i = 0; i < colors.Count; i++)
{
    MessageBox.Show(colors[i]);
}

Insert List elements

You can use insert(index, item) method to insert an in the specified index.

colors.Insert(1, "violet");

In the above code, the colour “violet” inserted in the index position 1.

How to sort a C# List

You can use the sort() method of C# List for ordering items in the List.

colors.Sort();

How to remove an item from List collection?

Remove() can use to remove the item from List collection.

colors.Remove("violet");

How to check if an item exists in the List collection?

You can use List.Contains() methods to check an item exists in the List

if (colors.Contains("Blue"))
{
    MessageBox.Show("Blue color exist in the list");
}

How to copy an Array to a List collection?

string[] strArr = new string[3];
strArr[0] = "Red";
strArr[1] = "Blue";
strArr[2] = "Green";
//here to copy array to List
List<string> arrlist = new List<string>(strArr);

How to Convert List to String in C#

You can convert a C# List to a string using the following method.

 string combindedString = string.Join(",", colors);

The output looks like “Red, Blue, Green.”

You can replace the separator to any character instead of “,”

Convert List to Array in C#

You can convert a C# List to an Array using toArray() method.

string[] arr = colors.ToArray();

How to empty a list in C#?

Finally, the precise method removes all the items from List collection.

arrlist.Clear ();

List Vs Array

Arrays are memory-efficient. Lists are built on top of arrays. Because of this, Lists use more memory to store the same data. The array is useful when you know the data is fixed length, or unlikely to grow much. It is better when you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever. On the other hand, if you don’t know how many elements you’ll have, use List. Also, use a List any time you want to add/remove data, since resizing arrays is expensive.

If you are using foreach then the key difference is as follows:

Array:

  • no object is allocated to manage the iteration
  • bounds checking is removed

List via a variable known to be List:

  • the iteration management variable is stack allocated
  • bounds checking is performed

List Vs ArrayList

In C# List is depend by array so the theoretical limit of size would be the limit of the array’s capacity. Appending elements is efficient because we are using the free slots at the end, but inserting elements can be slow because all elements in the List after the insertion point have to be shifted to make a free slot. In case of searching, it is efficient if the BinarySearch method is used on a list that has been sorted if you use any other search algorithm is inefficient because each item must be individually checked.

How to get duplicate items from a list using LINQ

List<String> duplicates = lst.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

The GroupBy keyword groups the elements that are the same together, and the Where keyword filters out those that only appear once, leaving you with only the duplicates.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List < string > colors = new List < string > ();

            //add items in a List collection
            colors.Add("Red");
            colors.Add("Blue");
            colors.Add("Green");

            //insert an item in the list
            colors.Insert(1, "violet");

            //retrieve items using foreach loop
            foreach (string color in colors)
            {
                MessageBox.Show(color);
            }

            //remove an item from list
            colors.Remove("violet");

            //retrieve items using for loop
            for (int i = 0; i < colors.Count; i++)
            {
                MessageBox.Show(colors[i]);
            }

            if (colors.Contains("Blue"))
            {
                MessageBox.Show("Blue color exist in the list");
            }
            else
            {
                MessageBox.Show("Not exist");
            }

            //copy array to list
            string[] strArr = new string[3];
            strArr[0] = "Red";
            strArr[1] = "Blue";
            strArr[2] = "Green";
            List < string > arrlist = new List < string > (strArr);

            foreach (string str in strArr)
            {
                MessageBox.Show(str);
            }

            //call clear method
            arrlist.Clear ();

            MessageBox.Show(arrlist.Count.ToString ());
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More