เมธอด Single() คืนค่าองค์ประกอบเพียงตัวเดียวที่ตรงตามเงื่อนไข หากมีมากกว่าหนึ่งองค์ประกอบที่ตรงเงื่อนไข จะโยนข้อผิดพลาด (exception)
นี่คืออาร์เรย์สตริงของเรา:
string[] str = { "jack", "tom", "henry", "time"};
ตอนนี้ ให้ใช้เมธอด Single() เพื่อดึงแต่ละองค์ประกอบ จากนั้นเราใช้ Lambda Expression เพื่อคำนวณองค์ประกอบที่มีความยาวมากกว่า 4
str.AsQueryable().Single(name => name.Length > 4);
ตัวอย่าง
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
string[] str = { "jack", "tom", "henry", "time"};
// หาสตริงที่ความยาวมากกว่า 4
string res = str.AsQueryable().Single(name => name.Length > 4);
Console.WriteLine(res);
}
}
ผลลัพธ์
henry