Home > Backend Development > C#.Net Tutorial > How to check if an item exists in a C# list collection?

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

PHPz
Release: 2023-09-18 22:49:07
forward
1353 people have browsed it

如何检查 C# 列表集合中是否存在某个项目?

Set up a list -

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

Now use the Contains method to check if an item exists in the list.

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

The following code is used to check whether an item exists in a C# list.

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...");
      foreach(string list in list1) {
         Console.WriteLine(list);
      }

      Console.Write("Finding an item in the list...");
      if (list1.Contains("Adams") == true) {
         Console.WriteLine("Item exists!");
      } else {
         Console.WriteLine("Item does not exist!");
      }
   }
}
Copy after login

The above is the detailed content of How to check if an item exists in a C# list collection?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template