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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP