Using List in C#, Easy Tutorial

Understanding List in C#:

Firstly we have to know that what are list and why it is used. List is same as Arrays bit dynamic in nature, means that you do not have to give it a size at the time of initialization. The List automatically changes its size at run time when we are inserting data in it and increases its size with every single data entry.

List can be of any data type and it is generic in Nature.

Declaration of List C#:

List<int> mylist = new List<int>(); // we give data type between <> in List

 Insertion in List C#:

            int a = 5;
            int[] arr = {3,2,6};
            mylist.Add(a);   // We use Add to add a single item
            mylist.AddRange(arr);  // We use AddRange to add collection od data

Functions in List C# using Loops:

We can do display, search or any other thing as per our need using Loops in List C#.  We can use both foreach and for loop same as arrays. Examples are given:

Display in List C#:

            foreach(int z in mylist)

Searching in List C#:

        public void search()
            int index;
            Console.WriteLine("Enter element you want to search?");
            int data = Convert.ToInt32(Console.ReadLine());
            for (int i = 0; i < mylist.Count; i++)
                if (mylist[i] == data)
                    index = i;  // storing index number of searched item so that we can use it later

You can also get the index by using built in function IndexOf, Example:

            int index = mylist.IndexOf(3); // -1 will be returned if not found

Deletion in List C#:

List can be deleted using Clear() function. example :

Conversion in List C#:

List can be converted to array of same data type, For Example:

           int[] myarray = mylist.ToArray(); // converting List "mylist" to array "myarray"

Array can be converted to List of same data type, For Example:

           List<int> lis = myarray.ToList();  // converting array "myarray" to list "mylist"

Learn how to create a Windows Service using C# here

 Thank You for Reading. Like this if you understood, It helps us a lot to keep us motivated


Post a Comment