I often see people using Where.FirstOrDefault()
to do a search and grab the first element. Why not just use Find()
? Is there an advantage to the other? I couldn't tell a difference.
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();
}
}
}
list.FirstOrDefault(x => x == "item3");
is more concise than using both.Where
and.FirstOrDefault
. – Kirk WollFind
predates LINQ. (it was available in .NET 2.0 and you couldn't use lambdas. You were forced to use normal methods or anonymous methods) – Kirk Woll