เมธอดจะคืนค่าองค์ประกอบเฉพาะของลำดับ หากองค์ประกอบไม่มีอยู่ในลำดับ ค่าเริ่มต้นจะถูกส่งคืน
เรามีอาร์เรย์สตริงสองอันที่นี่
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