Languages
[Edit]
EN

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

6 points
Created by:
JustMike
26120

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

1. Linq Min example

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

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

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

Output:

index=2; value=11

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 findMinItem(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=2; value=11

3. References

  1. Enumerable.Min Method - Microsoft Docs
  2. List<T>.IndexOf Method - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join