Home > Backend Development > C++ > How to Find the Maximum Value and its Index in an Unsorted C# Array?

How to Find the Maximum Value and its Index in an Unsorted C# Array?

Linda Hamilton
Release: 2024-12-29 11:10:11
Original
534 people have browsed it

How to Find the Maximum Value and its Index in an Unsorted C# Array?

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

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!

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