DEV Community

seonglinchua
seonglinchua

Posted on

Mastering List<T> in C# for Coding Interviews

πŸ“˜ List in C# β€” The Dynamic Array You Need to Know

List<T> is the most flexible and commonly used collection in C#. It’s a dynamic array that automatically resizes and provides indexed access.


βœ… When to Use List

Use Case Why Use List
Need dynamic resizing Automatically expands as needed
Index-based access Like arrays, but flexible
Frequent insert/remove Especially at the end
Storing objects or models Generic and powerful

✍️ Declaring & Initializing List

// Create an empty list
List<int> numbers = new List<int>();

// Initialize with values
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
Enter fullscreen mode Exit fullscreen mode

πŸ” Adding, Removing, and Accessing Elements

numbers.Add(10);       // Add to end
numbers.AddRange(new int[] { 20, 30 }); // Add multiple

numbers.Remove(20);    // Remove by value
numbers.RemoveAt(0);   // Remove by index

int first = numbers[0];         // Access
numbers[1] = 100;               // Update
Enter fullscreen mode Exit fullscreen mode

πŸ” Iterating Through List

for (int i = 0; i < names.Count; i++)
{
    Console.WriteLine(names[i]);
}

foreach (string name in names)
{
    Console.WriteLine(name);
}
Enter fullscreen mode Exit fullscreen mode

πŸ” Searching and Sorting

bool exists = names.Contains("Bob");     // true
int index = names.IndexOf("Charlie");    // 2

names.Sort();       // Sort alphabetically
names.Reverse();    // Reverse order
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Interview Example: Merge Intervals (List of Lists)

public int[][] Merge(int[][] intervals)
{
    if (intervals.Length <= 1) return intervals;

    Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
    var merged = new List<int[]>();
    var current = intervals[0];

    foreach (var interval in intervals)
    {
        if (interval[0] <= current[1])
            current[1] = Math.Max(current[1], interval[1]);
        else
        {
            merged.Add(current);
            current = interval;
        }
    }
    merged.Add(current);

    return merged.ToArray();
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Summary

Feature Syntax Example
Declare List<int> list = new List<int>();
Add list.Add(value), list.AddRange(...)
Access/Update list[i], list[i] = value
Remove list.Remove(value), list.RemoveAt(i)
Sort/Reverse list.Sort(), list.Reverse()

Up next: Dictionary β€” your go-to structure for frequency maps and lookup-based problems like Two Sum and Group Anagrams.

Top comments (0)