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

I created a simple class representing the 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 them. I want to extract the smallest date, how do I do this?

+4
source share
3 answers

You can use Enumerable.Min ( null values ​​will be ignored if all values ​​are non-zero):

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

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

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

If you need the latest date, you can use Enumerable.OrderByDescending .

+23
source

you can use the extension method Min () LINQ:

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

I see that the date property is NULL, so if you want to avoid zeros, use the following:

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

+3
source

You can do it simply with Linq. Given that you need an 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 correct syntax is above), you can do it like this:

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

Enjoy your day :-)

+1
source

All Articles