Home > Backend Development > C++ > How Can I Find the Maximum Value and Its Index in a C# Array?

How Can I Find the Maximum Value and Its Index in a C# Array?

Mary-Kate Olsen
Release: 2024-12-26 21:01:16
Original
959 people have browsed it

How Can I Find the Maximum Value and Its Index in a C# Array?

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template