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