Finding Highest Array Value and its Index in C#
Determining the highest value and its corresponding index in an unsorted array is a common task in programming. Consider the array int[] anArray = { 1, 5, 2, 7 }. To identify the largest value (7) and its index (3), there is a straightforward approach:
Firstly, leverage the Max() method provided by the Linq namespace. This method conveniently returns the highest value within the array. To incorporate this functionality, ensure that your code includes the directive using System.Linq;.
Once the maximum value is obtained, proceed to determine its index using the IndexOf() method. However, as anArray is an array, this method is not directly applicable. Therefore, convert the array to a list using ToList() and then utilize IndexOf to retrieve the index of the highest value.
To summarize, the following code snippet accomplishes both tasks:
int maxValue = anArray.Max(); int maxIndex = anArray.ToList().IndexOf(maxValue);
With this approach, both the highest value and its index can be efficiently determined from an unsorted array in C#.
The above is the detailed content of How Can I Find the Maximum Value and Its Index in a C# Array?. For more information, please follow other related articles on the PHP Chinese website!