Gayan
Gayan

Reputation: 2860

Using Linq .Min() to get Min Date

i'm trying to get min date from a collection

someCollection.Min(d => d.Dates.Select(c => c.ReservationDateStart)).FirstOrDefault();

but it returns exception

At least one object must implement IComparable

based on this i came up with that Min didn't work but how we get min object from collection based on it's property collection of min?

my collection is something like this

public class InfoDatesViewModel
    {
        public DateTime OccureFrom { get; set; }
        public DateTime OccureTo { get; set; }
        public string RecurreFrom { get; set; }
        public string RecurreTo { get; set; }
        public int RecurrentType { get; set; }
        public bool IsFullDay { get; set; }
        public int ReservedQuantity { get; set; }
        public ReservedDateViewModel[] Dates { get; set; }
    }

and ReservedDateViewModel is

public class ReservedDateViewModel
    {
        public bool IsAvailable { get; set; }
        public DateTime ReservationDate { get; set; }
        public DateTime ReservationDateEnd { get; set; }
        public DateTime ReservationDateStart { get; set; }
    }

Upvotes: 0

Views: 2089

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

The problem is that InfoDatesViewModel.Dates is a collection, so you can't compare it directly.

When having a collection of collections, you can flatten them using the SelectMany operator:

someCollection.SelectMany(c => c.Dates).Min(d => d.ReservationDateStart);

Upvotes: 4

Related Questions