Gilbert Tordeur (7) [Avatar] Offline

Context = VB2008 and SQL Server 2000.

Problem : How to get the maximum value with Linq in VB2008 ?

The MSDN help gives the following example :

Dim latestHireDate = Aggregate emp In db.Employees _
Into Max(emp.HireDate)

I have adapted this example to my need, changing the date by a year number,
and adding some Where clause:

Dim ContexteFluide As New FluideDataContext(.OpenFluide)
Dim NumAnneeMax = Aggregate Declaration In ContexteFluide.DeclarationFluide
Where ( _
(Declaration.DflNumSociete = .NumSocieteCourante) _
And (Declaration.DflNumSite = .NumSiteCourant) _
) _
Into Max(Declaration.DflNumAnnee)

It works fine if at least one record is found. But I get an
InvalidOperationException if no record at all match the selection criteria.

How can I change the statement to avoid the need of a Try statement, and
(for example) to receive a Nothing value in NumAnneeMax (that will be of
type Nullable(Of Integer) ?)

Thank you for your help.
fabrice.marguerie (224) [Avatar] Offline
Re: Linq and Max, in VB 2008
Bonjour Gilbert,

Would the following solution work in your case:
Dim query = _
From declaration In ContexteFluide.DeclarationFluide _
Where ( _
(declaration.DflNumSociete = .NumSocieteCourante) _
And (declaration.DflNumSite = .NumSiteCourant) _
) _
Select Declaration.DflNumAnnee

Dim numAnneeMax = query.Max(Function(num) CType(num, Nullable(Of Integer)))
The idea is to convert the data to nullable objects to avoid the issue with LINQ to SQL.
More info:

Gilbert Tordeur (7) [Avatar] Offline
Re: Linq and Max, in VB 2008
Merci Fabrice.
Testé et adopté.
And congratulations for your book, that I had a great pleasure to read. My only regret is that it is mainly written in C# instead of VB (even if the VB code is available by download, but it is not as easy to access when reading the book).
fabrice.marguerie (224) [Avatar] Offline
Re: Linq and Max, in VB 2008
I'm glad to learn that your enjoyed our book.
Covering both VB and C# at the same level in the book would have been difficult. I think that a distinct VB edition would have been better.