How to use Last() to find the last element of int array that matches a condition in C#

2 Answers

0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 3, 4, 5, 6, 7 };

            int last = arr.Last();
            int lastEven = arr.Last(element => element % 2 == 0);

            Console.WriteLine(last);
            Console.WriteLine(lastEven);
        }
    }
}


/*
run:

7
6

*/

 



answered Feb 23, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 3, 4, 5, 6, 7 };

            int last = arr.Last();
            int lastEven = arr.Last(element => element % 2 == 0);
            int lastOdd = arr.Last(element => element % 2 != 0);

            Console.WriteLine(last);
            Console.WriteLine(lastEven);
            Console.WriteLine(lastOdd);
        }
    }
}


/*
run:

7
6
7

*/

 



answered Feb 23, 2017 by avibootz
...