List in C# plays a very important role in data storage and retrieval. Following are some important points on the generic list ( List
Syntax:
List<T> list_name = new List<T>();
Explanation: In the above statement List< T > is a generic list of type T. Here T can be of any type like int, string, etc. And list_name is the user-given name of the list. We initialize a list with the help of a ‘ new ’ keyword.
We can also create a list with the help of the IList< T > interface, such as:
IList<T> list_name = new List<T>();
In order to work with List< T >, first, we need to import the System.Collections.Generic namespace in our program.
There are many ways to create list in C#, such as :
Example:
List<int> lstNum = new List<int>();
The above statement will create a list of an integer with default capacity. If the capacity of the list is not defined by the user then the size of the list increases every time when an item is added to the list.
ASP.NET Training (9 Courses, 19 Projects).NET Training Program (5 Courses, 19 Projects)
Example:
lstNum.Add(1); lstNum.Add(2); lstNum.Add(3);
Creating a list with capacity defined by the user.
Example:
List<string> lstString = new List<string>(3);
The above statement will create a list of a string with capacity three. The capacity expands automatically when more than three elements are added to the list. We can also add items to the list while initializing it.
List<string> lstString = new List<string>(3) { "Neha", "Shweta", "Megha" };
We can also create a list with the help of another collection of elements.
Example:
//string array of names string[] names = {"Neha", "Shweta", "Megha"}; //creating list by using string array List<string> lstNames = new List<string>(names);
We can add another collection of elements to a list using the AddRange() method.
Example:
string[] names = {"Neha", "Shweta", "Megha"}; List<string> lstNames = new List<string>(); //adding elements of string array to list lstNames.AddRange(names);
Let us discuss some important methods of List class as follows:
This method is used to add an object at the end of the list. It can add a null value for a reference type.
Example:
using System; using System.Collections.Generic; public class ListDemo { public static void Main() { List<int> lstNum = new List<int>(){1, 2, 3, 4}; //Adding 5 at the end of list lstNum.Add(5); foreach(int num in lstNum) { Console.WriteLine(num); } } }
Output:
This method is used to remove all the elements from the list.
Example:
using System; using System.Collections.Generic; public class ListDemo { public static void Main() { List<int> lstNum = new List<int>(){1, 2, 3, 4, 5}; //removing all elements from the list lstNum.Clear(); if(lstNum.Count > 0) Console.WriteLine("List is not empty"); else Console.WriteLine("List is empty"); } }
Output:
This method is used to insert an element at the specified position in the list. It takes two arguments, the first argument is the index number where you want to insert an element and the second argument is the element itself.
Example:
using System; using System.Collections.Generic; public class ListDemo { public static void Main() { List<string> lstCities = new List<string>(){"Mumbai", "Pune", "Bengaluru"}; //inserting element at third position lstCities.Insert(2, "Chennai"); foreach(string city in lstCities) { Console.WriteLine(city); } } }
Output:
This method is used to remove an item at the specified position from the list.
Example:
using System; using System.Collections.Generic; public class ListDemo { public static void Main() { List<string> lstCities = new List<string>() {"Mumbai","Pune","Bengaluru"}; Console.WriteLine("Initial list values"); foreach(string city in lstCities) { Console.WriteLine(city); } //removing element at second position lstCities.RemoveAt(1); Console.WriteLine("\nAfter removing element at second position"); foreach(string city in lstCities) { Console.WriteLine(city); } } }
Output:
This method is used to sort the elements of the list using default comparer.
Example:
using System; using System.Collections.Generic; public class ListDemo { public static void Main() { List<string> lstCities = new List<string>(){"Mumbai","Pune","Bengaluru"}; Console.WriteLine("Initial list values"); foreach(string city in lstCities) { Console.WriteLine(city); } //sorting elements in ascending order lstCities.Sort(); Console.WriteLine("\nList after sorting in ascending order"); foreach(string city in lstCities) { Console.WriteLine(city); } //sorting elements in descending order by calling Reverse() lstCities.Reverse(); Console.WriteLine("\nList after sorting in descending order"); foreach(string city in lstCities) { Console.WriteLine(city); } } }
Output:
In the above program, first, we sorted the list in ascending order using Sort(). Now to sort the list in descending order we called Reverse() method on the sorted list. We can sort a list of type int, string, etc. using Sort() method but to sort a list of type custom objects, we need to implement an IComparable interface or we can also use LINQ. We can sort this type of list in another way as shown in the below example:
Example:
using System; using System.Collections.Generic; public class Student { public string Name { get; set; } public int Marks { get; set; } public Student(string name, int marks) { Name = name; Marks = marks; } } public class ListDemo { public static void Main() { List<Student> lstStudents = new List<Student>(); lstStudents.Add(new Student("Neha", 90)); lstStudents.Add(new Student("John", 75)); lstStudents.Add(new Student("Kate", 88)); lstStudents.Add(new Student("Arya", 70)); //sorting students in ascending order of their marks lstStudents.Sort(CompareMarks); foreach (Student student in lstStudents) { Console.WriteLine(student.Name + ": " + student.Marks); } } public static int CompareMarks(Student student1, Student student2) { return student1.Marks.CompareTo(student2.Marks); } }
Output:
List< T > is a generic collection of elements of a specified type. The elements of the list can be accessed through its index number using ‘for’ or ‘foreach’ loop. We can perform many operations on a list such as add, insert, search, sort, etc. It’s dynamic sized.
Das obige ist der detaillierte Inhalt vonListe in C#. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!