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)
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With