Reputation: 1483
I need to be able to add an unkown number of where clauses to a Linq query. Currently I have been trying to combine the queries using Concat(). For example:
var r1 =
from field in db.fields
where ID == 1
select field;
var r2 =
from field in db.fields
where ID == 2
select field
var r3 = r1.Concat(r2);
This is giving me odd results, so I know that there must be a better way to do this. Is there any way to do something along the lines of an "accumulating result"; such as:
r1 = r1 + r2
Where r1 gets all of the results it had before plus all of the results from r2. This would allow me to iterate through a list of "where" filters and combine them as an OR statement would. Thanks to anyone who can help!
Upvotes: 1
Views: 3953
Reputation: 4309
In case you are trying to do r1 = r1 + r2, then you should use some immediate query execution behavior, like ToList
. You see, In LINQ the query is executed only if needed, and not at the place it was defined.
So the query should look like
r1 = r1.Union(r2).ToList()
Also, notice the use of Union instead of Concat. "Concat method returns all the original elements in the input sequences. The Union method returns only unique elements." (from msdn)
EDIT: Or you could use PredicateBuilder to build the OR-ed predicate, somthing like
var predicate = PredicateBuilder.False<Field>();
foreach(Expression<Func<Field,Boolean>> filt in filters){
predicate = predicate.Or(filt);
}
var result = db.fields.Where(predicate);
Upvotes: 1
Reputation: 14457
It sounds like you are looking for the Union operator:
var r1 = Context.Fields.Where<FieldObject>(f => f.ID == 1).Select<FieldObject, Field>(f => f.Field);
var r2 = Context.Fields.Where<FieldObject>(f => f.ID == 2).Select<FieldObject, Field>(f => f.Field);
var r3 = r1.Union<Field>(r2);
Upvotes: 2