如何檢查某個項是否存在於 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!");       }    } }

更新於:2020 年 6 月 22 日

14K+ 瀏覽次數

開啟您的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.