Mastering C# List: A Comprehensive Reference
Classified in Computers
Written on in
English with a size of 54.79 KB
Understanding the C# List<T>
- The List<T> is a collection of strongly typed objects that can be accessed by index and includes methods for sorting, searching, and modifying the list.
- It is the generic version of the ArrayList, found within the
System.Collections.Genericnamespace. - The List<T> performs faster and is less error-prone than the
ArrayList. - Because it is a generic collection, you must specify a type parameter for the data it stores.
Creating a List and Adding Elements
List<int> primeNumbers = new List<int>();
primeNumbers.Add(1); // Adding elements using Add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);Using Collection Initializer Syntax
var bigCities = new List<string>()
{
"New York",
"London",
"Mumbai",
"Chicago"
};Adding Custom Class Objects
var students = new List<Student>()
{
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};Accessing a List by Index
List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 2
Console.WriteLine(numbers[2]); // prints 5
Console.WriteLine(numbers[3]); // prints 7Accessing a List Using LINQ ForEach
List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
// Using foreach LINQ method
numbers.ForEach(num => Console.WriteLine(num + ", "));
// prints 1, 2, 5, 7, 8, 10,Accessing a List Using a For Loop
List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
// Using for loop
for(int i = 0; i < numbers.Count; i++)
Console.WriteLine(numbers[i]);Accessing Custom Class Objects by Index
var students = new List<Student>()
{
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};
Console.WriteLine(students[0].Id); // prints 1
Console.WriteLine(students[0].Name); // prints BillAccessing Custom Objects via LINQ Query
var students = new List<Student>()
{
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};
// Get all students whose name is Bill
var result = from s in students
where s.Name == "Bill"
select s;
foreach(var student in result)
Console.WriteLine(student.Id + ", " + student.Name);