How would I create a where clause with multiple ORs based off a List?
I know it won't work, but here's what I'm trying to achieve. I haven't found a suitable method for doing it yet. For every one of the strings passed in, I need to add an OR where clause. The list could contain multiple tag strings and I need the query to add an OR where clause for each of them.
public void GetItems(List<String> tagsToGet){
var tagQuery = from tag in ParseObject.GetQuery("Tag")
foreach(string tagToGet in tagsToGet){
where tag.Get<string>("name") == tagToGet || // next loop
}
select tag;
}
You can go with method chain:
public void GetItems(List<String> tagsToGet){
var tagQuery = ParseObject.GetQuery("Tag");
foreach(string tagToGet in tagsToGet)
{
tabQuery = tabQuery.Where(w => w.Get<string>("name") == tagToGet).AsEnumerable(); || // next loop
}
}
This should work:
where tagsToGet.Contains(tag.Get<string>("name"))
or possibly
where t=> tagsToGet.Any(ttg => String.Equals(ttg, t.Get<string>("name"), StringComparison.CurrentCultureIgnoreCase))
Obviously you can replace the comparison with any other way you prefer.
Another alternative, more linq-tastic:
var tagQuery = from tag in ParseObject.GetQuery("Tag")
join tagToGet in tagsToGet
on tagToGet equals tag.Get<string>("name")
select tag;
Have a look at PredicateBuilder . The second example should fit your requirements:
IQueryable<Product> SearchProducts (params string[] keywords)
{
var predicate = PredicateBuilder.False<Product>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
return dataContext.Products.Where (predicate);
}
If querying with Entity Framework, change the last line to this:
return objectContext.Products.AsExpandable().Where (predicate);
You want to use Dynamic LINQ. Get NuGet package System.Linq.Dynamic and see an example here: http://weblogs.asp.net/ricardoperes/dynamic-linq
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.