C# List and Dynamic Collections — Complete Beginner Guide
Learning Objectives
- Create and use List of T
- Add, insert, remove, and search items
- Loop over lists with foreach
- Know when list beats array
- Avoid common list pitfalls
Why Lists Matter
Arrays are fixed in size. Real programs often need to grow and shrink data while running. List of T is the go to dynamic collection for ordered items.
using System.Collections.Generic;
List<string> names = new List<string>();
names.Add("Asha");
names.Add("Ben");
names.Add("Cara");
Console.WriteLine(names.Count);
List lives in the Generic namespace, so include the using directive at the top of your file.
Creating a List
You can start empty or seed with values.
List<int> scores = new List<int> { 90, 85, 78 };
List<string> cities = new List<string> { "Delhi", "Pune" };
Console.WriteLine(scores.Count);
Console.WriteLine(cities[0]);
The text between angle brackets names the element type the list will hold.
Adding Items
List<string> tasks = new List<string>();
tasks.Add("Learn C sharp");
tasks.Add("Build a console app");
tasks.Add("Write tests");
foreach (string task in tasks)
{
Console.WriteLine(task);
}
Add always appends to the end.
Insert at a position
tasks.Insert(0, "Install SDK");
Console.WriteLine(tasks[0]);
Removing Items
List<int> nums = new List<int> { 1, 2, 3, 4 };
nums.Remove(3);
nums.RemoveAt(0);
foreach (int n in nums)
{
Console.WriteLine(n);
}
Remove deletes the first matching value. RemoveAt deletes by index.
Searching and Checking
List<string> tools = new List<string> { "dotnet", "git", "vscode" };
bool hasGit = tools.Contains("git");
int index = tools.IndexOf("vscode");
bool anyLong = tools.Exists(t => t.Length > 4);
Console.WriteLine(hasGit);
Console.WriteLine(index);
Console.WriteLine(anyLong);
Exists takes a condition, often written as a lambda. You will study lambdas more in later lessons.
Updating by Index
Lists support indexed assignment like arrays.
List<double> prices = new List<double> { 10.5, 20.0 };
prices[1] = 22.5;
Console.WriteLine(prices[1]);
Sorting and Reversing
List<int> values = new List<int> { 5, 1, 4, 2 };
values.Sort();
foreach (int v in values)
{
Console.Write(v + " ");
}
values.Reverse();
Console.WriteLine();
Sort changes the list in place. Reverse flips the order after sorting or anytime you like.
List vs Array
| Feature | Array | List |
|---|---|---|
| Size | Fixed | Grows and shrinks |
| Syntax | Type with brackets | Generic list type |
| Performance | Very fast indexing | Slight overhead, flexible |
| Best for | Known fixed data | Changing collections |
Choose array when the size never changes. Choose list when you need flexibility.
Capacity and Performance
List manages an internal array behind the scenes. When it fills, it grows automatically. If you know roughly how many items you will add, you can set capacity to reduce resizes.
List<int> buffer = new List<int>(1000);
This is an optimization detail, not a requirement for beginners.
Common Mistakes
Forgetting the Generic namespace
If the compiler does not know List, add using System.Collections.Generic at the top.
Index out of range after remove
Always recheck Count after removals before assuming an index still exists.
List<string> items = new List<string> { "a", "b" };
items.Remove("a");
Console.WriteLine(items.Count);
Console.WriteLine(items[0]);
Mixing types
A List of int cannot hold text. Pick the element type that matches your data.
Practice Snippet
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");
colors.Insert(1, "Yellow");
colors.Remove("Green");
foreach (string c in colors)
{
Console.WriteLine(c);
}
Console.WriteLine(colors.Count);
Predict the output before you run the program.
Key Takeaways
💡
- List of T stores ordered, strongly typed, growable data
- Add appends; Insert places; Remove and RemoveAt delete
- Count reports size; indexes start at zero like arrays
- Prefer list when size changes; prefer array when it does not
- Include the Generic using directive to resolve List
Practice Questions
- What namespace must you import to use List?
- What is the difference between Remove and RemoveAt?
- How do you get the number of items in a list?
- When is an array a better choice than a list?
- Build a list of three favorite foods, insert a fourth at the start, then print all items.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions