मैं अक्सर लोगों Where.FirstOrDefault()को खोज करने और पहले तत्व को हथियाने के लिए उपयोग करता हूं। सिर्फ उपयोग क्यों नहीं Find()? क्या दूसरे के लिए एक फायदा है? मैं एक अंतर नहीं बता सकता।
namespace LinqFindVsWhere
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.AddRange(new string[]
{
"item1",
"item2",
"item3",
"item4"
});
string item2 = list.Find(x => x == "item2");
Console.WriteLine(item2 == null ? "not found" : "found");
string item3 = list.Where(x => x == "item3").FirstOrDefault();
Console.WriteLine(item3 == null ? "not found" : "found");
Console.ReadKey();
}
}
}
FindLINQ को दर्शाता है। (यह .NET 2.0 में उपलब्ध था और आप लैम्ब्डा का उपयोग नहीं कर सकते। आपको सामान्य तरीकों या अनाम विधियों का उपयोग करने के लिए मजबूर किया गया था)
list.FirstOrDefault(x => x == "item3");दोनों का उपयोग करने की तुलना में अधिक संक्षिप्त है.Whereऔर.FirstOrDefault।