What are Add, Remove methods in C# lists?

CsharpProgrammingServer Side Programming

The List<T> is a collection in C# and is a generic collection. The add and remove methods are used in C# lists for adding and removing elements.

Let us see how to use Add() method in C#.

Example

 Live Demo

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football");
      sports.Add("Tennis");
      sports.Add("Soccer");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

Output

Football
Tennis
Soccer

Let us see how to use Remove() method in C#.

Example

 Live Demo

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football"); // add method
      sports.Add("Tennis");
      sports.Add("Soccer");
      Console.WriteLine("Old List...");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
      Console.WriteLine("New List...");
      sports.Remove("Tennis"); // remove method
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

Output

Old List...
Football
Tennis
Soccer
New List...
Football
Soccer
raja
Published on 18-Sep-2018 11:46:27
Advertisements