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...
Find the maximum value of column: select max(age) from employee; Above example will return largest value for column age of employee table.
The MAX() function returns the largest value of the selected column.
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.
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.
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 );
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);
}
}
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