Using FirstOrDefault : FirstOrDefault « LINQ « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;

public class MainClass{
   public static void Main(){
            int[] numbers = { 1, 3, 5, 7, 9 };
            var query = numbers.FirstOrDefault(n => n % 2 == 0);
            Console.WriteLine("The first even element in the sequence");
            Console.Write(query);
            Console.WriteLine("The last odd element in the sequence");
            query = numbers.LastOrDefault(n => n % 2 == 1);
            Console.Write(query);
   }
}








22.44.FirstOrDefault
22.44.1.Using FirstOrDefault
22.44.2.FirstOrDefault: get the first or the default
22.44.3.FirstOrDefault with a Not Found Element
22.44.4.FirstOrDefault returns null when an Element Is Found
22.44.5.FirstOrDefault with string operator
22.44.6.FirstOrDefault with Condition
22.44.7.Get a customer in Africa with FirstOrDefault