The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Gilbert Tordeur (7) [Avatar] Offline
#1
Hello.

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.
Gilbert
fabrice.marguerie (224) [Avatar] Offline
#2
Re: Linq and Max, in VB 2008
Bonjour Gilbert,

Would the following solution work in your case:
[pre]
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)))
[/pre]
The idea is to convert the data to nullable objects to avoid the issue with LINQ to SQL.
More info: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338103

Fabrice
Gilbert Tordeur (7) [Avatar] Offline
#3
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).
Gilbert
fabrice.marguerie (224) [Avatar] Offline
#4
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.