Use First, Last with expression : First « LINQ « C# / C Sharp






Use First, Last with expression

 
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, 2, 3, 4, 5, 6, 7, 8, 9 };
       var query = numbers.First();
       Console.WriteLine("The first element in the sequence");
       Console.Write(query);
       query = numbers.Last();
       Console.WriteLine("The last element in the sequence");
       Console.Write(query);
       Console.WriteLine("The first even element in the sequence");
       query = numbers.First(n => n % 2 == 0);
       Console.Write(query);
       Console.WriteLine("The last even element in the sequence");
       query = numbers.Last(n => n % 2 == 0);
       Console.Write(query);
   }
}

 








Related examples in the same category

1.First with string method
2.retrieves all strings in an array whose length matches that of the shortest string
3.Use First to return the first matching element as a Product
4.First operator