Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select max age C#

Tags:

c#

list

max

I created a list<T> that contains a collection of objects that have this properties: X, Y, Z

I want to find out which object in the collection has the greatest Z

I tried to use the Max() function but I don't understand how it's used...

like image 505
Killercode Avatar asked Sep 28 '09 20:09

Killercode


People also ask

How do I SELECT Max age in SQL?

Find the maximum value of column: select max(age) from employee; Above example will return largest value for column age of employee table.

What does MAX() do in SQL?

The MAX() function returns the largest value of the selected column.

How to fetch MAX value in SQL?

Discussion: To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

When to use MAX in SQL?

MAX() function The aggregate function SQL MAX() is used to find the maximum value or highest value of a certain column or expression. This function is useful to determine the largest of all selected values of a column.


2 Answers

Max is used to find the maximum value of a property. Once you have the maximum value you can select those objects whose value matches using the Where clause.

var maxZ = list.Max( obj => obj.Z );
var maxObj = list.Where( obj => obj.Z == maxZ );
like image 189
tvanfosson Avatar answered Sep 20 '22 15:09

tvanfosson


To get the object with the greatest Z value you sort on the Z value in descending order and get the first item:

TypeOfObject oldest = list.OrderByDescending(x => x.Z).First();

Edit:
Changed it to use the IEnumerable.OrderByDescending method instead of List.Sort.

Edit 2:
If you want performance, this is about four times faster than the fastest LINQ solution:

int high = Int32.MinValue;
List<TypeOfObject> highest = new List<TypeOfObject>();
foreach (TypeOfObject v in list) {
   if (v.Z >= high) {
      if (v.Z > high) highest.Clear();
      high = v.Z;
      highest.Add(v);
   }
}
like image 30
Guffa Avatar answered Sep 21 '22 15:09

Guffa