I was wondering on how FirstOrDefault extension method works? Which one of the following algorithms does it follows?
Use:
var arr = new[] {1, 2, 3, 4, 5, 6, 7};
return arr.FirstOrDefault(x => x%2 == 0);
Algorithm 1:
for(int i = 0; i < arr.Length; i++)
{
if(arr[i] % 2 == 0)
return arr[i];
}
return 0;
Algorithm 2:
var list = new List<int>();
for(int i = 0; i < arr.Length; i++)
{
if(arr[i] % 2 == 0)
list.Add(arr[i]);
}
return list.Count == 0 ? 0 : list[0];
Does the FirstOrDefault algorithm is smart enough to choose the optimal one or it strictly follow any one of these algorithms?