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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短