Reputation: 3288
Suppose I have one class “Person”
………
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
and suppose I have list “listOfPerson”
which contain say 15 person…
List<Person> listOfPerson = new List<Person>();
Now I trying to get Object person form this List with Max Age…..
Read Carefully I an not just need Max Age…… but entire object….so I can also access the name of the person with max Age…….
Thanks………
Upvotes: 0
Views: 199
Reputation: 14162
If the list is short then ordering and selecting the first (as previously mentioned) is probably the easiest.
If you have a longer list and sorting it starts to get slow (which is probably unlikely), you could write your own extension method to do it (I used MaxItem because I think just Max would conflict with existing LINQ methods, but I'm too lazy to find out).
public static T MaxItem<T>(this IEnumerable<T> list, Func<T, int> selector) {
var enumerator = list.GetEnumerator();
if (!enumerator.MoveNext()) {
// Return null/default on an empty list. Could choose to throw instead.
return default(T);
}
T maxItem = enumerator.Current;
int maxValue = selector(maxItem);
while (enumerator.MoveNext()) {
var item = enumerator.Current;
var value = selector(item);
if (value > maxValue) {
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
Or, if you need to return all the maximum items:
public static IEnumerable<T> MaxItems<T>(this IEnumerable<T> list, Func<T, int> selector) {
var enumerator = list.GetEnumerator();
if (!enumerator.MoveNext()) {
return Enumerable.Empty<T>();
}
var maxItem = enumerator.Current;
List<T> maxItems = new List<T>() { maxItem };
int maxValue = selector(maxItem);
while (enumerator.MoveNext()) {
var item = enumerator.Current;
var value = selector(item);
if (value > maxValue) {
maxValue = value;
maxItems = new List<T>() { item };
} else if (value == maxValue) {
maxItems.Add(item);
}
}
return maxItems;
}
Upvotes: 1
Reputation: 126884
Person oldest = listOfPerson.OrderByDescending(person => person.Age).First();
From comments
And suppose i say....all the person with max age...(list of person with max Age from given list of person)? Thanks
In this case, it's worth it to find the maximum age and then filter on it. There are various approaches, but a straightforward method is
int maxAge = listOfPerson.Max(person => person.Age);
var oldestPeople = listOfPerson.Where(person => person.Age == maxAge); // .ToList()
Include the optional ToList()
extension if it's important that the result be a list instead of an IEnumerable<Person>
.
Upvotes: 4
Reputation: 11155
listOfPerson.OrderByDescending(x=>x.Age).First();
Upvotes: 1