π 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" };
π 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
π Iterating Through List
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine(names[i]);
}
foreach (string name in names)
{
Console.WriteLine(name);
}
π Searching and Sorting
bool exists = names.Contains("Bob"); // true
int index = names.IndexOf("Charlie"); // 2
names.Sort(); // Sort alphabetically
names.Reverse(); // Reverse order
π§ͺ 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();
}
π 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)