Possible Duplicate:
LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value
I have the following class:
class Product
{
public string ProductName { get; set; }
public DateTime ActivationDate { get; set; }
}
Then I create and fill a List<Product>
and I would like to get the ProductName
from the Product
with the latest ActivationDate
.
Product.Where(m => m.ActivationDate == Max(m.ActivationDate)).Select(n => n.ProductName)
Product.Max(m => m.ActivationDate).Select(n => n.ProductName)
but bot methods do not work. Does anybody know a way to achieve this task?
You can OrderByDescending
the List<Product>
on the ActivationDate Field and then take FirstOrDefault()
Product.OrderByDescending(p => p.ActivationDate).FirstOrDefault();
For a more simpler version there is an extension method
MaxBy
Product.MaxBy(p => p.ActivationDate);
If you can do this:
class Product : IComparable<Product>
{
public string ProductName { get; set; }
public DateTime ActivationDate { get; set; }
public int CompareTo(Product other)
{
return this.ActivationDate.CompareTo(other.ActivationDate);
}
}
Then it is just this:
var max = products.Max(p => p).ProductName;
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