C# 程式演示 Exists 屬性的使用


C# 中的 Exists 屬性是一個非常有用的屬性,它用於檢查集合中是否存在任何元素滿足給定條件。此屬性是 C# 中 List<T> 類的一部分,並返回一個布林值,指示列表中是否存在任何滿足指定條件的元素。在本文中,我們將探討在 C# 程式中使用 Exists 屬性。

什麼是 Exists 屬性?

Exists 屬性是一個布林屬性,它在 C# 中的 List<T> 類中定義。它接受一個委託作為引數,並返回一個布林值,指示列表中是否存在任何元素與給定條件匹配。

Exists 屬性的語法

public bool Exists(Predicate<T> match)

示例:使用 Exists 屬性檢查列表中是否存在任何元素

讓我們來看一個如何使用 Exists 屬性檢查列表中是否存在任何元素的示例。

using System;
using System.Linq;
using System.Collections.Generic;

class Program {
   static void Main(string[] args) {
      List<string> fruits = new List<string>() { "apple", "banana", "orange", "grape", "mango" };
   
      bool exists = fruits.Exists(f => f.Equals("apple"));
   
      if (exists) {
         Console.WriteLine("Apple exists in the list");
      }
      else {
         Console.WriteLine("Apple does not exist in the list");
      }
   }
}

在此程式碼中,我們有一個名為 fruits 的字串列表。我們使用 Exists 屬性來檢查元素“apple”是否存在於列表中。我們傳遞一個 lambda 表示式,該表示式檢查列表中每個元素是否等於“apple”。

輸出

Apple exists in the list

示例:使用 Exists 屬性檢查列表中是否存在任何元素滿足條件

現在,讓我們來看一個如何使用 Exists 屬性檢查列表中是否存在任何元素滿足條件的示例。

using System;
using System.Linq;
using System.Collections.Generic;

class Program {
   static void Main(string[] args) {
      List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
   
      bool exists = numbers.Exists(n => n > 3);
   
      if (exists) {
         Console.WriteLine("There exists an element in the list greater than 3");
      }
      else {
         Console.WriteLine("There is no element in the list greater than 3");
      }
   }
}

在此程式碼中,我們有一個名為 numbers 的整數列表。我們使用 Exists 屬性來檢查列表中是否存在任何元素大於 3。我們傳遞一個 lambda 表示式,該表示式檢查列表中每個元素是否大於 3。

輸出

There exists an element in the list greater than 3

結論

Exists 屬性是一個強大的屬性,可用於檢查集合中是否存在任何元素滿足給定條件。在本文中,我們探討了在 C# 程式中使用 Exists 屬性。我們瞭解瞭如何檢查列表中是否存在元素以及如何檢查列表中是否存在任何元素滿足條件。

更新於: 2023年5月4日

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告