Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get from a List<t> the record with the maximum value of a specific property [duplicate]

Tags:

c#

linq

max

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?

like image 930
CiccioMiami Avatar asked Dec 09 '22 22:12

CiccioMiami


2 Answers

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);
like image 146
V4Vendetta Avatar answered Mar 09 '23 00:03

V4Vendetta


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;
like image 37
Tomas Grosup Avatar answered Mar 09 '23 01:03

Tomas Grosup