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();
}
}
}
Where is the
Findmethod onIEnumerable<T>? (Rhetorical question.)The
WhereandFirstOrDefaultmethods are applicable against multiple kinds of sequences, includingList<T>,T[],Collection<T>, etc. Any sequence that implementsIEnumerable<T>can use these methods.Findis available only for theList<T>. Methods that are generally more applicable, are then more reusable and have a greater impact.FindonList<T>predates the other methods.List<T>was added with generics in .NET 2.0, andFindwas part of the API for that class.WhereandFirstOrDefaultwere added as extension methods forIEnumerable<T>with Linq, which is a later .NET version. I cannot say with certainty that if Linq existed with the 2.0 release thatFindwould never have been added, but that is arguably the case for many other features that came in earlier .NET versions that were made obsolete or redundant by later versions.