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: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!
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.
Source: stackoverflow.com
Related Query
- 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?
- 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
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?
- When using LINQ, what is the difference between && and multiple where clauses?
- Differences in LINQ syntax between VB.Net and C#
- LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
- Entity Framework Linq Query to List - Error when using contains: Only primitive types, enumeration types and entity types are supported
- 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 is the difference between using Join in Linq and "Olde Style" pre ANSI join syntax?
- Using C# , LINQ how to pick items between markers again and again?
- Duplicate rows when using orderby, Skip() and Take() with LINQ
- Differences between LINQ to Objects and LINQ to SQL queries
- How can I code an outer join using LINQ and EF6?
- BestPractice: Pros and Cons for using AutoMapper or LINQ (LINQ to Objects) for mapping between a Domain Model and a Presentation Model
- How to distinguish between a found 0 and default(int) when using methods like FindLast?
- Using LINQ to search between two Dates and Times
- Is a full list returned first and then filtered when using linq to sql to filter data from a database or just the filtered list?
- What are the major differences between Data Access Application Block, NHibernate, ADO.NET Entity Framework and LINQ to SQL?
- Linq sub query when using a repository pattern with EF code first
- How do I get rid of "Possible System.NullReferenceException" warnings when using LINQ and ReSharper?
- Differences between LINQ where and where method on a collection
- When using the Linq methods .Any(<predicate>) and .All(<predicate>) on an IList, are the predicates applied to the list in a strict sequence?
- Using LINQ get the differences between two tables
- LINQ to SQL bug (or very strange feature) when using IQueryable, foreach, and multiple Where
More Query from same tag
- NHibernate + LINQ - efficient work with related collections
- How to get distinct List from a custom list?
- c# and mongodb: Aggregates with filter
- Use lambda syntax to retrieve a property from an anonymous type in vb.net
- Linq to XML query nested elements
- Linq to return ALL pairs of elements from two lists?
- LINQ group data into a list of objects containing a list + selecting specific original data
- Strange LINQ Exception (Index out of bounds)
- Creating a List<T> that matches items first, then adding in the rest using LINQ
- Iterate N numbers and do a sum on it using LINQ
- 'AnonymousType#1[]' to 'System.Collections.Generic.List<QuestHub.Class1>
- What is proper way to write this linq lambda expression and deal with nulls?
- Retrieving Data From Multiple Tables in a LINQ to SQL query
- searching a List<>
- LINQ to SQL not creating Transactions
- LINQPad - can't understand the query generated
- Use LINQ to convert List of Dictionary to strongly Typed Class object List
- Select integers from string[], and return int[]
- asp.net LinqDataSource query multiple tables with join
- Can someone help me refactor this C# linq business logic for efficiency?
- Override LINQ .Include(), possible?
- How to use Select in linq
- Find a combination of two elements that have not been viewed together (LINQ, SQL or C#)
- The name of the => operator in C#
- Calling stored procedure from C# is not working
- Linq way to check a property of one set against a property of another set
- Result consisted of more than one row when executing linq query against mysql database?
- Remove Duplicate Entries of 'Multicolumn'-List with LINQ
- LINQ - Add property to results
- Easy way to convert a Dictionary<string, string> to xml and vice versa