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

PHPz
PHPz 转载
2023-09-18 22:49:07 829浏览

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

设置一个列表 -

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

现在使用 Contains 方法检查列表中是否存在某个项目。

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

以下代码用于检查 C# 列表中是否存在某项。

示例

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!");
      }
   }
}

以上就是如何检查 C# 列表集合中是否存在某个项目?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除