C# List

C# Code Snippets List
Share:

About

In this code snippet, we’ll find out how to use lists in C#.

Lists are similar to arrays, but unlike arrays, they are more flexible. You can add and remove items from lists without having to make a new list and destroying the entire old one every time you add or remove an element. Also, lists have a lot of useful methods such as find(), exists(), sort(), …  You can use intellisense in Visual Studio to explore all the methods available.

Now let’s look at the code example to see how to use lists.

Code:

using System;
using System.Collections.Generic;

namespace List
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create list.
            //List<(data type)> (list name)
            List<MyClass> myList = new List<MyClass>();

            //Add a few items to the list.
            myList.Add(new MyClass("1"));
            myList.Add(new MyClass("2"));
            myList.Add(new MyClass("3"));

            Console.WriteLine("Items in list:");
            Console.WriteLine("");

            //Show items in list.
            showListItems(myList);

            Console.WriteLine("Removing item from list.");
            Console.WriteLine("");

            //Remove item from list 
            myList.RemoveAt(1);

            Console.WriteLine("Items in list after removal:");
            Console.WriteLine("");

            //Other things you can do with lists.

            //myList.Reverse(); //Reverses order.
            //myList.Count(); //Gets size of list.
            //myList.Sort(); //Sorts items in list.

            //Show items in list.
            showListItems(myList);

            Console.ReadLine();
        }

        public static void showListItems(List<MyClass> myList)
        {
            //Access items from list.
            foreach (var item in myList)
            {
                Console.WriteLine(item.Text);
            }

            Console.WriteLine("");
        }
    }

    class MyClass
    {
        public MyClass(string text)
        {
            Text = text;
        }

        public string Text { get; set; }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger