Linq – How to Select Min and Max date values in Linq Query

linqlinq-to-sql

I am moving from SQL to Linq and I need some help. I am testing both Linq-to-SQL and Linq-to-Entities. I want to try both to decide which one suits me best. Your help is appreciated. Thanks

What is the correct syntax (in vb.net if possible) to select the minimum date value from a table?

Dim mydata As New DataClassesDataContext
Dim myresult = From cv In mydata.T1s
                       Select cv.DATE1, cv.Date2, cv.Datex
myresult=Dump()

I have tried I have tried to use

Select amin=cv.DATE1.Min(), amax=cv.Date1.Max(), bmin=cv.Date2.Min(), etc....

is giving this error 'Min' is not a member of 'Date'.

The Data That I want to get min and max on is below:

IOrderedQueryable<VB$AnonymousType_0<DateTime,DateTime>> (16 items) 

Date1                   Date2
17/Oct/09 12:00:00 AM   23/Oct/09 12:00:00 AM
10/Jan/09 12:00:00 AM   15/Feb/09 12:00:00 AM
27/Mar/09 12:00:00 AM   27/Mar/09 12:00:00 AM
30/May/09 12:00:00 AM   30/May/09 12:00:00 AM
25/Jan/09 12:00:00 AM   25/Mar/09 12:00:00 AM
01/Nov/09 12:00:00 AM   01/Nov/09 12:00:00 AM
21/Feb/09 12:00:00 AM   04/Mar/09 12:00:00 AM
02/Mar/09 12:00:00 AM   09/Mar/09 12:00:00 AM
07/Jul/09 12:00:00 AM   07/Jul/09 12:00:00 AM
27/Sep/09 12:00:00 AM   27/Sep/09 12:00:00 AM
05/Nov/09 12:00:00 AM   05/Nov/09 12:00:00 AM
15/Apr/09 12:00:00 AM   15/Apr/09 12:00:00 AM
08/Jun/09 12:00:00 AM   08/Jun/09 12:00:00 AM
07/Jul/09 12:00:00 AM   07/Jul/09 12:00:00 AM
30/Jul/09 12:00:00 AM   30/Jul/09 12:00:00 AM
04/Nov/09 12:00:00 AM   04/Nov/09 12:00:00 AM

Now resolved, but this is not a the perfect solution, it seems that I needed to do a seperate query for each column that requires aggreagate function :

Sub Main

Dim mm = (From cv In T1s 
Select Datez = (cv.Date1)).Min()

Dim mm1 = (From cv In T1s 
Select Datez = (cv.Date1)).Max()

Dim mm2 = (From cv In T1s 
Select Datez = (Date2)).Min()

Dim mm3 = (From cv In T1s 
Select Datez = (Date2)).Max()
mm.dump()
mm1.dump()
mm2.dump()
mm3.dump()

End Sub

The Results are below

10/Jan/09 12:00:00 AM
05/Nov/09 12:00:00 AM
15/Feb/09 12:00:00 AM
05/Nov/09 12:00:00 AM

Best Answer

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)