0
0
C Sharp (C#)programming~5 mins

List generic collection in C Sharp (C#)

Choose your learning style9 modes available
Introduction
A List is like a flexible row of boxes where you can store items in order. You can add, remove, or find items easily.
When you want to keep a collection of items that can grow or shrink.
When you need to access items by their position quickly.
When you want to add items at the end or remove items from anywhere.
When you want to loop through items in order.
When you want a simple way to store and manage a group of similar things.
Syntax
C Sharp (C#)
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> listName = new List<int>();
    }
}
Replace with the type of items you want to store, like int, string, or a custom class.
List is part of System.Collections.Generic namespace, so include it with using.
Examples
Create a list of integers and add two numbers.
C Sharp (C#)
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
Create an empty list of strings.
C Sharp (C#)
List<string> names = new List<string>();
// Empty list with no items yet
Create a list with one item already inside.
C Sharp (C#)
List<int> singleItemList = new List<int> { 5 };
An empty list has zero items.
C Sharp (C#)
List<int> emptyList = new List<int>();
// List is empty, Count is 0
Sample Program
This program creates an empty list of strings, adds three fruit names, and prints the count and items before and after adding.
C Sharp (C#)
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> fruits = new List<string>();
        Console.WriteLine("Before adding items:");
        Console.WriteLine($"Count: {fruits.Count}");

        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        Console.WriteLine("After adding items:");
        Console.WriteLine($"Count: {fruits.Count}");

        Console.WriteLine("Items in the list:");
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
OutputSuccess
Important Notes
Adding an item to a List is usually very fast (amortized O(1) time).
Accessing an item by index is very fast (O(1) time).
Removing items can be slower because the list shifts items to fill gaps (O(n) time).
Common mistake: Forgetting to include System.Collections.Generic namespace.
Use List when you need a flexible, ordered collection. Use arrays if size is fixed and performance is critical.
Summary
List<T> stores items in order and can grow or shrink.
You can add, remove, and access items by position easily.
List<T> is simple and useful for many common collection tasks.