Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Max value from objects array in C#

Tags:

c#

I have an array which have objects, these objects have a string, a integer and a char properties.

Person[] people = new Person[1]; //Declare the array of objects

[...] This code is irrelevant

Person person = new Person(name, age, gender); //This creates instance a new object
people.SetValue(person, i); //is just a variable which increase in a c
Array.Resize(ref people, people.Length + 1);  //Change array  size 
i++; // Autoincrement

[...] More code to fill the values that works

From all the objects person stored in people array, i want to get the person's age max value (age property is integer value)

like image 326
Mr_LinDowsMac Avatar asked Sep 13 '25 10:09

Mr_LinDowsMac


2 Answers

The easiest way is to use LINQ:

using System.Linq;

var maxVal = people.Max(x => x.Age); // get highest age
var person = people.First(x => x.Age == maxVal); // get someone with such an age
like image 73
jwaliszko Avatar answered Sep 15 '25 23:09

jwaliszko


I'm assuming that your Person class looks something like this: -

class Person
{
  public int Age { get; private set; }
  public string Name { get; private set; }
  public string Gender { get; private set; }

  // constructor etc
}

Improvements

If you have an Enumerable of Person, i.e. 'people', for which I recommend you use a container with an interface such as an IList, i.e: -

IList<Person> people = new List<Person>();

As this will save you from having to resize your array manually.

Solution

To acquire the greatest age, you can do something like: -

var max = people.Max(p => p.Age);

Further reading

This is a Linq query; more information can be found here: -

http://msdn.microsoft.com/en-gb/library/vstudio/bb397926.aspx

There are a lot of 'cool' things you can do with linq, such as selecting an enumerable of ages, i.e.

var ages = people.Select(p => p.Age);

This would return an enumerable containing the age of each person in your list. If you wanted all those over a certain age, you can use Where, i.e: -

var above = people.Where(p => p.Age > 65);
like image 26
chrisw Avatar answered Sep 15 '25 23:09

chrisw