C#SingleorDefault()方法
该方法返回序列的单个特定元素。如果序列中不存在该元素,则返回默认值。
这里有两个字符串数组。
string[] str1 = { "one" };
string[] str2 = { };检查第一个数组是否有单个元素,而第二个数组为空并使用SingleorDefault检查。
str2.AsQueryable().SingleOrDefault();
以下是显示SingleorDefault()方法用法的示例。
示例
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
string[] str1 = { "one" };
string[] str2 = { };
string res1 = str1.AsQueryable().Single();
Console.WriteLine("String found: "+res1);
string res2 = str2.AsQueryable().SingleOrDefault();
Console.WriteLine(String.IsNullOrEmpty(res2) ? "String not found" : res2);
}
}输出结果
String found: one String not found
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西