Identifying Maximum Value and Index in an Unsorted Array using C#
In C#, finding both the maximum value and its corresponding index in an unsorted numeric array is an essential task for various programming scenarios. Consider the unsorted array int[] anArray = { 1, 5, 2, 7 }, where you need to retrieve the highest value and its index, which in this case are 7 and 3, respectively.
Solution:
Although not considered an elegant approach, a straightforward solution involves leveraging the .Max() and .ToList().IndexOf() methods from the System.Linq namespace:
using System.Linq; int maxValue = anArray.Max(); int maxIndex = anArray.ToList().IndexOf(maxValue);
The .Max() method returns the maximum value in the array, while .ToList().IndexOf() retrieves the index of a specified element in the array, which is converted to a list using .ToList() for compatibility with the method.
The maxValue variable will now hold the largest value (7), and maxIndex will contain the index (3) of that value within the original unsorted array.
The above is the detailed content of How to Find the Maximum Value and its Index in an Unsorted C# Array?. For more information, please follow other related articles on the PHP Chinese website!