How to get the smallest date from a list of objects with a date?

I created a simple class that represents a project:

public class EntityAuftrag
{
    public string cis_auftrag { get; set; }
    public string bezeich { get; set; }
    public DateTime? dStart { get; set; }
    public DateTime? dEnd { get; set; }
    public decimal? aufstunde { get; set; }
    public int id_auftrag { get; set; }
    public string barcolor { get; set; }
}

Now I have a list of these. I want to extract the smallest date, how do I do that?

Answers


You can use Enumerable.Min (null values will be ignored unless all values are null):

DateTime? smallest = auftragList.Min(a => a.dStart);

Edit: if you want to find the object with the earliest(start) date, you can use OrderBy and First:

EntityAuftrag auft = auftragList.OrderBy(a => a.dStart).First();

If you want the latest date, you can use Enumerable.OrderByDescending instead.


you can use the Min() LINQ extension method:

collection.Min(item => item.dStart);

I see your date property is nullable, so if you want to avoid nulls, use the following:

collection.Where(item=> dStart.HasValue).Min(item => item.dStart);


You can do that simply with Linq. Given that you want the object with the earliest dStart, you can do the following:

List<EntityAuftrag> list = someSourceOfItems;

EntityAuftrag firstObject = list.OrderBy( i => i.dStart ).First() as EntityAuftrag;

Alternatively (not sure if the above is the right syntax), you can do it this way:

List<EntityAuftrag> list = someSourceOfItems;

EntityAuftrag firstObject = (from item in list
                            orderby item.dStart
                            select item).Single() as EntityAuftrag;

Enjoy your day :-)


Need Your Help

Division in Java always results in zero (0)?

java android division

The function below gets two values from sharedpreferences, weight and height, and I use these to calculate the BMI,

Can the SASS minifier remove duplicate styles?

css sass

I know that the css rules are fairly complex; however, couldn't the following css be fairly simply reduced in a number of ways by the optimizer? And if so, is there an option for it in the rails-sa...