In C# , you can delete an elment from the list in two methods.
RemoveAt :Takes the index number to be deleted as a parameter.
Remove: Deletes the desired value. If the value to be deleted is more than one in the list, it removes the first value. This method is often used to extract values with reference types. But it can also be used with value types.
RemoveAt Example: Item is removed from list by index number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Program { static void Main(string[] args) { List<string> names = new List<string>(); names.Add("Mike"); //index:0 names.Add("Marc"); //index:1 names.Add("Sammy");//index:2 names.Add("Linda");//index:3 names.RemoveAt(1); //Marc will removed names.ForEach(n=> Console.WriteLine(n)); Console.ReadLine(); } } |
Remove Example: Remove method generally uses for objects but you can use value types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Program { static void Main(string[] args) { List<string> names = new List<string>(); names.Add("Mike"); //index:0 names.Add("Marc"); //index:1 names.Add("Sammy");//index:2 names.Add("Linda");//index:3 names.Add("Sammy");//index:4 names.Remove("Sammy"); //First Sammy is removed names.ForEach(n=> Console.WriteLine(n)); Console.ReadLine(); } } |
Remove Example: Using with object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Person { string name; public Person(string n) { Name = n; } public string Name { get => name; set => name = value; } } class Program { static void Main(string[] args) { List<Person> names = new List<Person>(); Person person1 = new Person("Mike"); Person person2 = new Person("Marc"); Person person3 = new Person("Sammy"); Person person4 = new Person("Linda"); names.Add(person1); //index:0 names.Add(person2); //index:1 names.Add(person3);//index:2 names.Add(person4);//index:3 names.Remove(person3); names.ForEach(n => Console.WriteLine(n.Name)); Console.ReadLine(); } } |