How to check if an item exists in a C# list collection?

CsharpProgrammingServer Side Programming

Set a list −

List < string > list1 = new List < string > () {
   "Lawrence",
   "Adams",
   "Pitt",
   "Tom"
};

Now use the Contains method to check if an item exits in a list or not.

if (list1.Contains("Adams") == true) {
   Console.WriteLine("Item exists!");
}

The following is the code to check if an item exists in a C# list or not.

Example

using System;
using System.Collections.Generic;
public class Program {

   public static void Main() {
      List < string > list1 = new List < string > () {
         "Lawrence",
         "Adams",
         "Pitt",
         "Tom"
      };

      Console.Write("List...\n");
      foreach(string list in list1) {
         Console.WriteLine(list);
      }

      Console.Write("Finding an item in the list...\n");
      if (list1.Contains("Adams") == true) {
         Console.WriteLine("Item exists!");
      } else {
         Console.WriteLine("Item does not exist!");
      }
   }
}
raja
Published on 20-Aug-2018 16:58:03
Advertisements