score:0
Dim maxValue = ctype((From p In db.Products _
Where p.ProductID > 0 _
Select p.ProductID).Max(),Integer?)
score:0
HOLY crap what a PITA
Dim maxValue = (From p In db.Products _
Where p.ProductID > 300 _
Select new With {.id=CType(p.ProductID, Integer?)}).Max(Function(p) p.id)
There HAS to be a better way, right?
This has the desired Query plan and no error with null values, but can someone take a saw to it and clean it up?
score:0
C#
var maxValue = nw.Products
.Where(p => p.ProductID < 0)
.Select(p => p.ProductID)
.DefaultIfEmpty(int.MinValue)
.Max();
VB
Dim maxValue = nw.Products _
.Where(Function(p) p.ProductID < 0) _
.Select(Function(p) p.ProductID) _
.DefaultIfEmpty(Integer.MinValue) _
.Max()
score:0
How about a function that returns Nullable? (Sorry if the syntax isn't quite right.)
Function GetNullable(Of T)(val as Object)
If (val Is Nothing) Then
Return new Nullable(Of T)()
Else
Return new Nullable(Of T)(DirectCast(val, T))
End If
End Function
dim maxValue = (from p in Products
where p.ProductID < 0
select GetNullable(Of Integer)(p.ProductID)).Max()
score:1
Short answer: you can.
And then the long answer:
The only way that I can see that you can do this, is to create the lambda containing the TypeAs conversion explicitly. You can use the following extension methods to help you here:
<Extension()> _
Public Module TypeAsExtensions
<Extension()> _
Public Function SelectAs(Of TElement, TOriginalType, TTargetType)( _
ByVal source As IQueryable(Of TElement), _
ByVal selector As Expression(Of Func(Of TElement, TOriginalType))) _
As IQueryable(Of TTargetType)
Return Queryable.Select(source, _
Expression.Lambda(Of Func(Of TElement, TTargetType))( _
Expression.TypeAs(selector.Body, GetType(TTargetType)), _
selector.Parameters(0)))
End Function
<Extension()> _
Public Function SelectAsNullable(Of TElement, TType As Structure)( _
ByVal source As IQueryable(Of TElement), _
ByVal selector As Expression(Of Func(Of TElement, TType))) _
As IQueryable(Of TType?)
Return SelectAs(Of TElement, TType, TType?)(source, selector)
End Function
End Module
SelectAs
will in result in a TryCast(value, T)
for any T
, including Integer?
.
To use this, you would say
Dim maxValue = Products _
.Where(Function(p) p.ProductID < 0) _
.SelectAsNullable(Function(p) p.ProductID) _
.Max()
It ain't pretty, but it works. (This generates the same query as C# does.) As long as you don't call SelectAsNullable within a sub-query you're fine.
Another option could be to use
Dim maxValue = (From p In Products _
Where p.ProductID < 0
Select p.ProductID) _
.SelectAsNullable(Function(id) id) _
.Max()
The problem with this is that you get a double select, i.e.,
from p in Products
where p.ProductID < 0
select p.ProductID
select p.ProductID as int?
in C# parlance. It's quote possible LINQ to SQL still generate a subquery for this too.
Anyway, for this you can create an additional extension method
<Extension()> _
Public Function SelectAsNullable(Of TType As Structure)( _
ByVal source As IQueryable(Of TType)) _
As IQueryable(Of TType?)
Return SelectAs(Of TType, TType, TType?)(source, Function(x) x)
End Function
simplifying the LINQ query further
Dim maxValue = (From p In Products _
Where p.ProductID < 0
Select p.ProductID) _
.SelectAsNullable() _
.Max()
But as I said, this depends on the LINQ provider.
score:0
why not build the equivalent of an isnull check into the query?
dim maxValue = (from p in Products
where IIf(p.ProductID=Null, 0, p.ProductID) < 0
select p.ProductID)).Max()
Sorry if this doesn't work - I'm not actually testing it at this end, just throwing spaghetti on the wall!
Source: stackoverflow.com
Related Articles
- Differences between VB TryCast and C# "as" operator when using LINQ
- Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?
- How to reuse a linq expression for 'Where' when using multiple source tables
- Avoiding code repetition when using LINQ
- How to sum Timespan of subtraction between two datetimes in Linq when using group by?
- What are the difference between .Select, .Any, and .Count when using LINQ
- What are the differences between IEnumerable and Lists when using projections?
- What is the difference between a regular foreach and ForEach LINQ operator when it comes to async/await
- Linq sub query when using a repository pattern with EF code first
- Using LINQ get the differences between two tables
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- Using linq to retrieve differences between two lists with duplicates
- Null Reference error when using any operator other than == in linq
- Updating List using LINQ working when execute from Immediate window, not from code direct
- Getting InvalidCastException when trying to implement sorting in Entity Framework Code First using Linq
- Convert string[] to int[] in one line of code using LINQ
- Entity-framework code is slow when using Include() many times
- Ambiguous call when using LINQ extension method on DbSet<T>
- How to handle nulls in LINQ when using Min or Max?
- How to avoid Query Plan re-compilation when using IEnumerable.Contains in Entity Framework LINQ queries?
- Why does this Linq Cast Fail when using ToList?
- LINQ Between Operator
- Explicit/implicit cast operator fails when using LINQ's .Cast() operator
- Get the difference between two lists using LINQ
- Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?
- What actually happens when using async/await inside a LINQ statement?
- When using LINQ, what is the difference between && and multiple where clauses?
- Performance concern when using LINQ "everywhere"?
- Why do I have to copy "this" when using LINQ in a struct (and is it OK if I do)?
- Differences in LINQ syntax between VB.Net and C#
- How to bind an Event Handler to a dynamically created control inside of a collection?
- Pivot with LINQ and anonymous type?
- Sum List<T> Properties of each item in List<T>
- Build a list of criterias of optional filters for retrieving records nhibernate c#
- How to get the lowest future time (after now) from list of times with the current time
- Union two Lists of different types using a common property
- LINQ to Entities chaining commands with differing results
- Build List of missing values by scanning multiple collections
- What is the leading LINQ for JavaScript library?
- Select Distinct records by IDictionary<string,object> property in an object
- When does IEnumerable.Any(Func) return a value?
- Data manipulation in R in LINQ style
- assigning value from select linq query not updating the list
- Finding list of serial devices using LINQ
- Passing Array of Strings to LINQ Stored Procedure
- How can I return the contents of a collection inside a class using LINQ?
- Using LINQ to XML to traverse an HTML table
- Understanding the delete link in ASP.NET Dynamic Data scaffolds
- How do you make a cast in Lambda expressions?
- Count distinct values of a column in dataGridView using linq in .NET