C# SingleorDefault() 方法

csharpprogrammingserver side programming更新于 2025/9/14 14:05:00

该方法返回序列中的单个特定元素。如果元素不存在于序列中,则返回默认值。

这里有两个字符串数组。

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

相关文章