返回滿足條件唯一元素的 C# 程式
Single() 方法返回滿足條件的唯一元素。如果有多個元素滿足條件,將丟擲一個錯誤。
以下是我們的字串陣列。
string[] str = { "jack", "tom", "henry", "time"};
現在,使用 Single() 方法獲取每個元素。然後,我們使用 Lambda 表示式計算長度大於 4 的元素。
str.AsQueryable().Single(name => name.Length > 4);
例子
using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() { string[] str = { "jack", "tom", "henry", "time"}; // finding string whose length is greater than 4 string res = str.AsQueryable().Single(name => name.Length > 4); Console.WriteLine(res); } }
輸出
henry
廣告