How to detemine if sequence has items and if so return the value in LINQ
I currently do a lot of checks like so
If (From p In table Where p.USER_ID = LoggedInUser.USER_ID And p.DATE >= start And p.DATE < [end] And p.PR开发者_如何学COJECT_ID = ProjectId Select p.Field).Any Then
Me.lblOverallTotal.Text = (From p In table Where p.USER_ID = LoggedInUser.USER_ID And p.DATE >= start And p.DATE < [end] And p.PROJECT_ID = ProjectId Select p.Field).Sum.ToString
Else
Me.lblOverallTotal.Text = "0.0"
End If
however this results in two db hits. (one to determine if any and then one to calculate the sum.
I am sure there must be a less verbose method to do this but am struggling to find the synta
I would do something like (switching to C# as my VB is weak):
var sum = (from p in table
where p.USER_ID == LoggedInUser.USER_ID
&& p.DATE >= start
&& p.DATE < end
&& p.PROJECT_ID == ProjectId
select (float?)p.Field).Sum(); // use the correct data type here
LINQ-to-SQL (courtesy of SQL-server) has a foible where that gives null
if there are no results, i.e.
Me.lblOverallTotal.Text = (sum ?? 0).ToString();
The key point there (for reading it as VB): switch to Nullable-of-the-type
and Sum()
it. Then compare to null
.
精彩评论