A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 5.2: Lists

1. Creating a List:

To use lists in C#, you need to include the System.Collections.Generic namespace. Here's how you can create a list:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a list of integers
        List<int> numbers = new List<int>();

        // Adding elements to the list
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // Displaying elements
        Console.WriteLine("List elements:");
        foreach (int num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}


2. Initialization with Collection Initializer:

You can also initialize a list using a collection initializer:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };


3. Accessing Elements:

Access elements by index:

int firstElement = numbers[0];

4. List Methods:

  • Add: Adds an element to the end of the list.
  • Remove: Removes the first occurrence of a specific element.
  • Count: Gets the number of elements contained in the list.
  • Clear: Removes all elements from the list.

5. Iterating Through a List:

You can use a foreach loop or a for loop to iterate through the elements of a list:

foreach (int num in numbers)
{
    Console.WriteLine(num);
}


6. Sorting a List:

Use the Sort method to sort a list:

numbers.Sort();

7. Finding Elements:

Use methods like Contains, IndexOf, or Find to find elements:

bool containsThree = numbers.Contains(3);
int indexOfTwo = numbers.IndexOf(2);

8. List of Objects:

Lists can store any type of object. For example:

List<Person> people = new List<Person>(); people.Add(new Person("John", 25));

9. List of Strings:

Lists can be used to store strings as well:

List<string> words = new List<string> { "apple", "banana", "orange" };


10. Conclusion:

Lists in C# are powerful and flexible. They provide a convenient way to work with collections of items. By understanding the basic operations and methods, you can efficiently manipulate and retrieve data from lists in your C# programs.

This tutorial covers the fundamental aspects of working with lists in C#. Depending on your specific use case, you may need to explore additional features and methods provided by the List class in the C# documentation.