问题
I'm trying to figure out how to put multiple values into a WHERE
clause; this is the kind of thing you'd use a IN
clause for in SQL.
My current code:
if (Log.Count() == 1)
{
items = itemTable
.Where(Item => Item.id == Log[0].i_id)
.ToCollectionView();
}
else if (Log.Count() == 2)
{
items = itemTable
.Where(Item => Item.id == Log[0].i_id || Item.id == Log[1].i_id)
.ToCollectionView();
}
else if (Log.Count() == 3)
{
items = itemTable
.Where(Item => Item.id == Log[0].i_id || Item.id == Log[1].i_id || Item.id == Log[2].i_id)
.ToCollectionView();
}
It's pretty nasty. I can't find a way to put multiple values into that WHERE
clause without a big if statement. Any ideas?
回答1:
I faced the same issue. Using Any or Contains as others have suggested gave me a Not Supported Exception. I posted on the Azure Mobile Services forum and was told that IN is not supported yet. They advised I use an extension method which worked perfectly for me. Below is the code I used.
public static class Extensions
{
public async static Task<List<T>> In<T>(this IMobileServiceTable<T> table, List<int> ids)
{
var query = new StringBuilder("$filter=(");
for (int i = 0; i < ids.Count; i++)
{
query.AppendFormat("id eq {0}", ids[i]); //don't forget to url escape and 'quote' strings
if (i < ids.Count - 1)
{
query.Append(" or ");
}
}
query.Append(")");
var list = await table.ReadAsync(query.ToString());
var items = list.Select(i => MobileServiceTableSerializer.Deserialize<T>(i)).ToList();
return items;
}
}
Your list can be populated by calling the extension method like this:
FavoriteJokesList = await jokeItemTable.In(favoriteJokeIds);
Source: http://social.msdn.microsoft.com/Forums/en-US/azuremobile/thread/b573ff6c-1f6b-4846-b44d-4678e3d26f66
回答2:
Try this instead:
items = itemTable
.Where(Item => Log.Any(logItem => logItem.i_id == Item.id))
.ToCollectionView();
Edit: (in response to the "not supported exception")
You can try this alternative to see if the backend supports it:
var ids = Log.Select(logItem => logItem.i_id).ToList();
var items = itemTable
.Where(Item => ids.Contains(Item.id))
.ToCollectionView();
回答3:
items = itemTable.Where(Item => Log.Any(i => i.i_id == Item.id)).ToCollectionView();
回答4:
Just for the record, in the newest Version of the Azure Mobile Service SDK (1.0), this works:
var ids = Log.Select(logItem => logItem.i_id).ToList();
var items = await itemTable
.Where(Item => ids.Contains(Item.id))
.ToCollectionAsync();
来源:https://stackoverflow.com/questions/15172995/putting-multiple-values-in-a-where-clause-in-azure-mobile-services