Top community members

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

[Edit]
EN

C#/.NET - find highest array value and index

13 points
Created by:
JustMike
3364

In C#/.NET max value can be found in few ways.

1. Linq Max example

List<int> list = new List<int>()
{
	44, 33, 11, 22, 66, 55
};

int value = list.Max();
int index = list.IndexOf(value);

Console.WriteLine("index=" + index + "; value=" + value);

Output:

index=4; value=66

2. Custom example

public class Item
{
	public int Index { get; private set; }
	public int Value { get; private set; }

	public Item(int index, int value)
	{
		this.Index = index;
		this.Value = value;
	}
}

public static class ArrayUtils
{
	public static Item findMaxItem(List<int> list)
	{
		if (list.Count == 0)
			return null;

		int index = 0;
		int value = list[0];

		for (int i = 1; i < list.Count; ++i)
		{
			int entry = list[i];

			if (value > entry)
			{
				index = i;
				value = entry;
			}
		}

		return new Item(index, value);
	}
}

Example:

List<int> list = new List<int>()
{
	44, 33, 11, 22, 66, 55
};

Item item = ArrayUtils.findMaxItem(list);

Console.WriteLine("index=" + item.Index + "; value=" + item.Value);

Output:

index=4; value=66

3. References

  1. Enumerable.Max Method - Microsoft Docs
  2. List<T>.IndexOf Method - Microsoft Docs

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more