C# 程序返回唯一满足条件的元素
csharpprogrammingserver side programming更新于 2025/9/14 13:44:00
Single() 方法返回唯一满足条件的元素。如果可见多个这样的元素,则会引发错误。
以下是我们的字符串数组。
string[] str = { "jack", "tom", "henry", "time"};
现在,使用 Single() 方法获取每个元素。然后,我们使用 Lambda 表达式来计算长度大于四的元素。
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"};
// 查找长度大于 4 的字符串
string res = str.AsQueryable().Single(name => name.Length > 4);
Console.WriteLine(res);
}
}
输出
henry

