LINQ union with optional null second parameter - c#

I have two queries which return a collection of the same kind of object, after these two queries are done, I want to union them.
var results = from t in All()
where t.Blah.Contains(blahblah)
select t;
var results2 = from t in All()
where t.blah2.contains(blahblah)
select t;
return results.Union(results2);
It is possible that the second query could return no results, and be null.
It seems like if I try and perform a union with the two, if the second argument is null it will throw an ArgumentNullException.
The obvious answer would be to just to perform .ToList() on the second query to see if it contains anything. The problem with this is I am trying to take advantage of deferred execution and dont want to actually perform the query on the database at this stage.
Is there any way around this?
Edit - Solution
var results2 = from t in All()
where t.blah2!=null && t.blah2.Contains(blahblah)
select t;
Basically, the actual query was returning null as I was trying to do a contains on a null list
Thanks for the help!

results2 should return an empty list and not null when executing its query. The code you have should not cause any problems and should work just fine in all cases simple cases I can think of. Can you provide input which would cause the problem you are trying to solve?

Would the following not solve your problem?
return from t in All()
where t.Blah.Contains(blahblah) && t.Blah2.Contains(blahblah)
select t;
However, if results and results2 need to remain separate and you want to combine them:
return results.Union(results2 ?? Enumerable.Empty<TResult>());

var results = from t in All()
where t.Blah.Contains(blahblah)
select t;
var results2 = from t in All()
where t.blah2.contains(blahblah)
select t;
return (results2 != null || results2.Count() > 0) ? results.Union(results2) : results;
This will either return the union if there is something in results2, or just return the first result set.

Related

LINQ Query, Return Max Value with Where Clause

I'm working on an API; how can I set my linq query up to return the max value with a where condition?
See the example code below; I can return the max value of the field I want, but I need to filter it where another column value equals something.
var lot = db.ShrinkLotData.Where(x => x.SupplierMfgLot.ToLower() == label.SupplierMfgLot.ToLower() && x.CatPattern.ToLower() == label.CatPattern.ToLower())
.SingleOrDefaultAsync();
if (lot.Result == null)
{
var lots = db.ShrinkLotData.Where(x => x.CatPattern.ToLower() == label.CatPattern.ToLower());
int internallot = db.ShrinkLotData.Max(x => x.InternalLotNum).Value;
return Ok(lot);
}
return Ok(lot);
}
for the internallot, I want to return the highest value using similar syntax as the lots syntax.. (Where the catpattern equals a specific value)
What am I overlooking?
Thanks!
If I understand correctly, you basically need to use Where and Max together, so that you can select max value with a where condition.
db.ShrinkLotData.Where(x => x.CatPattern.ToLower() == label.CatPattern.ToLower()).Max(x => x.InternalLotNum).Value;
More Info : Composability of Queries:
..., you compose them in method syntax by
chaining the method calls together. This is what the compiler does
behind the scenes when you write queries by using query syntax. And
because a query variable does not store the results of the query, you
can modify it or use it as the basis for a new query at any time, even
after it has been executed.

Avoid "Nullable object must have a value." in Linq-To-Sql

I have a method query like this:
public IList<BusinessObject> GetBusinessObject(Guid? filterId)
{
using (var db = new L2SDataContext())
{
var result = from bo in db.BusinessObjects
where (filterId.HasValue)
? bo.Filter == filterId.value
: true
orderby bo.Name
select SqlModelConverters.ConvertBusinessObject(bo);
return result.ToList();
}
}
At runtime, this throws a System.InvalidOperationException: Nullable object must have a value.
Looking at the Debugger, the problem is my Where Clause: Linq To SQL tries to convert the entire thing to SQL, so even if filterId is NULL, it will still try to access filterId.value.
I thought/hoped the C# compiler/CLR would evaluate that where clause as a code block and only send one of the two branches to Linq To SQL, but that's not how it works.
My refactored version works, but is not very elegant:
public IList<BusinessObject> GetBusinessObject(Guid? filterId)
{
using (var db = new L2SDataContext())
{
var temp = from bo in db.BusinessObjects select bo;
if(filterId.HasValue) temp = temp.Where(t => t.Filter == filterId.Value);
var result = from t in temp
orderby t.Name
select SqlModelConverters.ConvertBusinessObject(bo);
return result.ToList();
}
}
I know that Lazy-Evaluation will make sure that only one query is really sent, but having that temp object in there isn't that great really.
Did you try:
where filterId == null || t.Filter == filterId
Your fix is exactly correct. You are effectively trying to build up a query dynamically, based on your function input. It's a good idea to omit the where clause instead of supplying WHERE TRUE anyway. If I were writing this query, I would go with your fixed version myself.
It's not as pretty as using the language keywords, but it's still the right way to approach the query in my opinion.

Lambda syntax in linq to db4o?

I know the following is possible with linq2db4o
from Apple a in db
where a.Color.Equals(Colors.Green)
select a
What I need however is something that allows me to build my query conditionally (like I can in other linq variants)
public IEnumerable<Apple> SearchApples (AppleSearchbag bag){
var q = db.Apples;
if(bag.Color != null){
q = q.Where(a=>a.Color.Equals(bag.Color));
}
return q.AsEnumerable();
}
In a real world situation the searchbag will hold many properties and building a giant if-tree that catches all possible combinations of filled in properties would be madman's work.
It is possible to first call
var q = (from Color c in db select c);
and then continue from there. but this is not exactly what I'm looking for.
Disclaimer: near duplicate of my question of nearly 11 months ago.
This one's a bit more clear as I understand the matter better now and I hope by now some of the db4o dev eyes could catch this on this:
Any suggestions?
Yes it's definitely possible to compose optimized LINQ queries using db4o. Granted that db is defined as follows:
IObjectContainer db;
Here is your query:
public IEnumerable<Apple> SearchApples (AppleSearchbag bag)
{
var query = db.Cast<Apple> ();
// query will be a Db4objects.Db4o.Linq.IDb4oLinqQuery<Apple>
if (bag.Color != null)
query = query.Where (a => a.Color == bag.Color);
return query;
}
In that case, the query will be executed whenever the returned enumerable is being iterated over.
Another possibility is to use the IQueryable mechanism, that has the advantage of being better recognized by developers:
public IQueryable<Apple> SearchApples (AppleSearchbag bag)
{
var query = db.AsQueryable<Apple> ();
// query will be a System.Linq.IQueryble<Apple>
if (bag.Color != null)
query = query.Where (a => a.Color == bag.Color);
return query;
}
In both cases, db4o will try to deduce an optimized query from the lambda expression upon execution, and if it fails, will fallback to LINQ to objects. The first one has the advantage of being more direct, by avoiding the queryable to LINQ to db4o transformation.

What does LINQ return when the results are empty

I have a question about LINQ query. Normally a query returns a IEnumerable<T> type. If the return is empty, not sure if it is null or not. I am not sure if the following ToList() will throw an exception or just a empty List<string> if nothing found in IEnumerable result?
List<string> list = {"a"};
// is the result null or something else?
IEnumerable<string> ilist = from x in list where x == "ABC" select x;
// Or directly to a list, exception thrown?
List<string> list1 = (from x in list where x == "ABC" select x).ToList();
I know it is a very simple question, but I don't have VS available for the time being.
It will return an empty enumerable. It won't be null. You can sleep sound :)
You can also check the .Any() method:
if (!YourResult.Any())
Just a note that .Any will still retrieve the records from the database; doing a .FirstOrDefault()/.Where() will be just as much overhead but you would then be able to catch the object(s) returned from the query
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
.ToList returns an empty list. (same as new List<T>() );
In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object.
in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
It won't throw exception, you'll get an empty list.

Linq returns list or single object

I have a Linq to Entities query like this one:
var results = from r in entities.MachineRevision
where r.Machine.IdMachine == pIdMachine
&& r.Category == (int)pCategory
select r;
Usually, I use the code below to check if some results are returned:
if (results.Count() > 0)
{
return new oMachineRevision(results.First().IdMachineRevision);
}
However, I'm getting NotSupportedException in the if condition.
The error message is: Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Note that pCategory is an Enum type.
EDIT: Based on your update, the error may be related to an enum in your entity class. See this blog entry for more information and a work-around. I'm leaving my original answer as an improvement on your query syntax.
Try doing the selection of the first entity in the query itself using FirstOrDefault and then check if the result is null.
int compareCategory = (int)pCategory; // just a guess
var result = (from r in entities.MachineRevision
where r.Machine.IdMachine == pIdMachine
&& r.Category == compareCategory
select r).FirstOrDefault();
if (result != null)
{
return new oMachineRevision(result.IdMachineRevision);
}
Why not just use FirstOrDefault() instead, and check for null? I can't see the benefit in querying for the count and then taking the first element.
In the standard implementation of linq, the operators "select" and "where" map to methods that return an IEnumerable or IQueryable. So standard linq methods when used should always return an IEnumerable from your query not a single object.
But linq methods that are candidates for the linq operators are not restricted to methods returning IEnumerables, any method returning anything can be chosen.
In case you have instance methods named "Select" and "Where" that return a single object or extensions methods that are specific to your class and return a single object those will be used instead of the standard linq ones.
My guess is that either a "Select" or "Where" method defined in your class is making linq return a single value instead of a IEnumerable<T>.
I didn't know different anonymous objects would be created depending on the query result. I guess they just wanted results to be of type IEnumerable
How about using a foreach?
var results = from r in entities.MachineRevision
where r.Machine.IdMachine == pIdMachine
&& r.Category == pCategory
select r;
foreach( var r in results )
{
yield return new oMachineRevision( r.IdMachineRevision );
}
This goes for all implicit types too. I must admit I keep forgetting this and that's how I came across this post.
if you have
class ClassA {
...
private string value;
...
public static implicit operator string(ClassA value)
{
return value.ToString();
}
...
}
you need to explictly cast the class to astring for comparison.
so I usually do this
var myClassAStr = myClassA.ToString();
var x = (from a in entites where a.ValToCompare == myClassAStr select a).first();
// do stuff with x
...
try using
IENumerable<MachineRevision> results = from r in entities.MachineRevision
...
instead.
I think its the var that's causing your issue.
Edit:
Read the error message. "Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."
One of these comparisions is with a type that is not int, string or guid. I'm guessing the Category.
r.Machine.IdMachine == pIdMachine && r.Category == pCategory
Interestingly, LinqToSql will allow this construction. Don't know why LinqToEntities does not support this.
I think you could also select the item you want another, simpler way by using lambda expressions.
var result = entities.MachineRevision
.Where(x => x.Machine.IdMachine == pIdMachine)
.Where(y => y.Category == (int)pCategory)
.FirstOrDefault();
if (result != null)
{
return new oMachineRevision(result.IdMachineRevision);
}
and then proceeding as you would normally

Categories