简体   繁体   中英

Select max age C#

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...

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);
   }
}
int maxAge = myList.Max(obj => obj.Z);

The parameter used is a lambda expression. This expression indicates which property to use(in this case, Z) to get the max value. This will get the maximum age. If you want the object which has the greatest age, you could sort by age and get the first result:

MyType maxItem = myList.OrderByDescending(obj => obj.Z).First();

If you do it this way, note that if two or more items all have the maximum age, only one of them is selected.

If can implement either IComparable<T> or IComparable on your class along these lines:

public Int32 CompareTo(MyClass other) {
  return Z.CompareTo(other.Z);
}

You can get the maximum value simply by calling (this will require using System.Linq ):

MyClass maxObject = list.Max();

This will only perform a single pass over your list of values.

It will largely depend on the type of X, if it is comparable:

var array = new[] { 
    new { X = "a", Y = "a", Z = 1 }, 
    new { X = "b", Y = "b", Z = 2 } 
};
var max = array.Max(x => x.Z);
Console.WriteLine(max);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM