List collection class in c#
List collection class in c#:-
  • A List class can be used to create a collection of any type.
  • For example, we can create a list of Integers, Strings and even complex types. The objects stored in the list can be accessed by index. Unlike arrays, lists can grow in size automatically. This class also provides methods to search, sort, and manipulate lists.

List is one of the generic collection classes present in System.Collections.Generic namespcae. There are several generic collection classes in System.Collections.Generic namespace as listed below.
  • Dictionary
  • List
  • Stack
  • Queue
  • etc

Example of Collection:-


using System;
using System.Collections.Generic;

class CollectionDemo
{
    public CollectionDemo()
    {
        Console.WriteLine("This is Collection Demo::\n");
    }
    public void Show()
    {
        // Create Customer Objects
        Customer customer1 = new Customer()
        {
            ID = 101,
            Name = "Santosh kumar singh",
            Salary = 10000
        };

        Customer customer2 = new Customer()
        {
            ID = 102,
            Name = "Reena kumari",
            Salary = 17000
        };

        Customer customer3 = new Customer()
        {
            ID = 104,
            Name = "Pragya kumari",
            Salary = 95000
        };

        Customer[] arrayCustomers = new Customer[2];
        arrayCustomers[0] = customer1;
        arrayCustomers[1] = customer2;
        // The following line will throw an exception, Index was outside the bounds of the array. 
        // This is because, arrays does not grow in size automatically.
        // arrayCustomers[2] = customer3;

        // Create a List of Customers. Here, we have set the size to 2. But when I add a third 
        // element the list size will automatically grow and we will not get an exception.
        List<Customer> listCustomers = new List<Customer>(2);
        // To add an element to the list, use Add() method.
        listCustomers.Add(customer1);
        listCustomers.Add(customer2);
        // Adding an element beyond the initial capacity of the list will not throw an exception.
        listCustomers.Add(customer3);

        // Items can be retrieved from the list by index. The following code will 
        // retrieve the first item from the list. List index is ZERO based.
        Customer cust = listCustomers[0];
        Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}",
                 cust.ID, cust.Name, cust.Salary);
        Console.WriteLine("------------------------------------------------");

        // foreach or for loop can be used to iterate thru all the items in the list
        // Using for loop
        for (int i = 0; i < listCustomers.Count; i++)
        {
            Customer customer = listCustomers[i];
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}",
                     customer.ID, customer.Name, customer.Salary);
        }
        Console.WriteLine("------------------------------------------------");

        // Using foreach loop
        foreach (Customer c in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------");

        // All generic collection classes including List are strongly typed. This means 
        // if you have created a List of type Customer, only objects of type Customer 
        // can be added to the list. If you try to add an object of different type you would 
        // get a compiler error. The following line will raise a compiler error.
        // listCustomers.Add("This will not compile");

        // If you want to insert an item at a specific index location of the list, use Insert() method. 
        // The following line will insert customer3 object at index location 1.
        listCustomers.Insert(1, customer3);
        Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}",
               listCustomers[1].ID, listCustomers[1].Name, listCustomers[1].Salary);
        Console.WriteLine("------------------------------------------------");

        // To get the index of specific item in the list use Indexof() method
        Console.WriteLine("Index of Customer3 object in the List = " +
                listCustomers.IndexOf(customer3));
        Console.WriteLine("------------------------------------------------");
    }
}


public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
}

class TestCollection
{
    static void Main(string[] args)
    {

        CollectionDemo objCollection = new CollectionDemo();
        objCollection.Show();
        Console.ReadLine();
    }
}


Collection Methods:-
  • Contains() function:- Use this function to check if an item exists in the list. This method returns true if the items exists, else false.
  • Exists() function:- Use this function, to check if an item exists in the list based on a condition. This method returns true if the items exists, else false.
  • Find() function:- This method searches for an element that matches the conditions defined by the specified lambda expression and returns the first matching item from the list.
  • FindLast() function:- This method searches for an element that matches the conditions defined by the specified lambda expression and returns the Last matching item from the list.
  • FindAll() function:- This method returns all the items from the list that match the conditions specified by the lambda expression.
  • FindIndex() function:- This method returns the index of the first item, that matches the condition specified by the lambda expression. There are 2 other overloads of this method which allows us to specify the range of elements to search, with in the list.
  • FindLastIndex() function:- This method returns the index of the last item, that matches the condition specified by the lambda expression. There are 2 other overloads of this method which allows us to specify the range of elements to search, with in the list.
  • Convert an array to a List:- Use ToList() method
  • Convert a list to an array:- Use ToArray() method
  • Convert a List to a Dictionary Use ToDictionary() method

Example of Collection (2):-

  

using System;
using System.Collections.Generic;
using System.Linq;

class CollectionDemoMethod
{
    public CollectionDemoMethod()
    {
        Console.WriteLine("This is collection methods demo::\n");
    }

    public void Show()
    {
          // Create Customer Objects
        Customer customer1 = new Customer()
        {
            ID = 101,
            Name = "Santosh kumar singh",
            Salary = 3000
        };

        Customer customer2 = new Customer()
        {
            ID = 102,
            Name = "Reena kumari",
            Salary = 20000
        };

        Customer customer3 = new Customer()
        {
            ID = 104,
            Name = "Manpreet kaur",
            Salary = 5200
        };

        Customer[] arrayCustomers = new Customer[3];
        arrayCustomers[0] = customer1;
        arrayCustomers[1] = customer2;
        arrayCustomers[2] = customer3;

        // To convert an array to a List, use ToList() method
        List<Customer> listCustomers = arrayCustomers.ToList();
        foreach (Customer c in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To convert a List to an array, use ToLArray() method
        Customer[] arrayAllCustomers = listCustomers.ToArray();
        foreach (Customer c in arrayAllCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To convert a List to a Dictionary use ToDictionary() method
        Dictionary<int, Customer> dictionaryCustomers = listCustomers.ToDictionary(x => x.ID);
        foreach (KeyValuePair<int, Customer> keyValuePairCustomers in dictionaryCustomers)
        {
            Console.WriteLine("Key = {0}", keyValuePairCustomers.Key);
            Customer c = keyValuePairCustomers.Value;
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To check if an item exists in the list use Contains() function
        // This method returns true if the items exists, else false
        if (listCustomers.Contains(customer2))
        {
            Console.WriteLine("Customer2 object exists in the list");
        }
        else
        {
            Console.WriteLine("Customer2 object does not exist in the list");
        }
        Console.WriteLine("------------------------------------------------------");

        // To check if an item exists in the list based on a condition, then use Exists() function
        // This method returns true if the items exists, else false
        if (listCustomers.Exists(x => x.Name.StartsWith("M")))
        {
            Console.WriteLine("List contains customer whose name starts with M");
        }
        else
        {
            Console.WriteLine("List does not contain a customer whose name starts with M");
        }
        Console.WriteLine("------------------------------------------------------");

        // Find() method searches for an element that matches the conditions defined by 
        // the specified lambda expression and returns the first matching item from the list
        Customer cust = listCustomers.Find(customer => customer.Salary > 5000);
        Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary);
        Console.WriteLine("------------------------------------------------------");

        // FindLast() method searches for an element that matches the conditions defined
        // by the specified lambda expression and returns the Last matching item from the list
        Customer lastMatch = listCustomers.FindLast(customer => customer.Salary > 5000);
        Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", lastMatch.ID, lastMatch.Name, lastMatch.Salary);
        Console.WriteLine("------------------------------------------------------");

        // FindAll() method returns all the items from the list that
        // match the conditions specified by the lambda expression
        List<Customer> filteredCustomers = listCustomers.FindAll(customer => customer.Salary > 5000);
        foreach (Customer cstmr in filteredCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cstmr.ID, cstmr.Name, cstmr.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // FindIndex() method returns the index of the first item, that matches the 
        // condition specified by the lambda expression. There are 2 other overloads 
        // of this method which allows us to specify the range of elements to 
        // search, with in the list.
        Console.WriteLine("Index of the first matching customer object whose salary is greater 5000 =" +
            listCustomers.FindIndex(customer => customer.Salary > 5000));
        Console.WriteLine("------------------------------------------------------");

        // FindLastIndex() method returns the index of the last item, 
        // that matches the condition specified by the lambda expression. 
        // There are 2 other overloads of this method which allows us to specify 
        // the range of elements to search, with in the list.
        Console.WriteLine("Index of the Last matching customer object whose salary is greater 5000 = " +
            listCustomers.FindLastIndex(customer => customer.Salary > 5000));
        Console.WriteLine("------------------------------------------------------");
    }
}

class TestColleciton
{
    static void Main(string[] args)
    {

        CollectionDemoMethod objCollMethod = new CollectionDemoMethod();
        objCollMethod.Show();
        Console.ReadLine();
    }
}

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
}