How to find the index and the largest (max) element in one dimensional int array with Linq in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 2, 234, 48, 17, 98, 918, 800, 12237, 100, 28 };

            var max = arr.Select((value, index) => new { value, index })
                  .OrderByDescending(vi => vi.value).First();

            Console.WriteLine("Largest : " + max.value);
            Console.WriteLine("Largest : " + max.index);
         }

    }
}
/*
run:
 
Largest : 12237
Index : 7
  
*/

 



answered Feb 3, 2016 by avibootz
...