이 메서드는 시퀀스의 단일 특정 요소를 반환합니다. 요소가 시퀀스에 없으면 기본값이 반환됩니다.
여기에 두 개의 문자열 배열이 있습니다.
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