Generic List<T> class Features
- It belongs to System.Collections.Generic namespace.
- It is type-safe because it is generic and and each item added to List must belong to the type specified for type argument.
- List item has an index value which is decided when the item is added to the List.
- It provides Add, Remove, Contains etc. methods to add, remove items or to check if an item exists etc.
In the following example, List generic collection initialization, its methods and properties are shown.
List<int> and List<string> Examples
List<int> voterlist = new List<int>();
voterlist.Add(1010151);
voterlist.Add(1010191);
voterlist.Add(1010221);
List<string> surnames = new List<string>();
surnames.Add("Gupta");
surnames.Add("Ambani");
surnames.Add("kapoor");
List<Student> Example
class Student
{
public int Id { get; set; }
public string Name { get; set; } = "Unknown";
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Object Initializer
Student s1 = new Student() { Id = 1, Age = 14, Name = "Ajay" };
Student s2 = new Student() { Id = 2, Age = 12, Name = "Rajesh" };
Student s3 = new Student() { Id = 3, Age = 13, Name = "Amar" };
Student s4 = new Student() { Id = 4, Age = 17, Name = "Jyoti" };
List<Student> students = new List<Student>();
students.Add(s1);
students.Add(s2);
students.Add(s3);
students.Add(s4);
//display students details
foreach (var student in students)
{
Console.Write(student.Id + " ");
Console.Write(student.Name + " ");
Console.Write(student.Age + " ");
Console.WriteLine();
}
Console.ReadKey();
}
}
No comments:
Post a Comment