I'm trying to do the reverse of the Select method: to project bunch of items based on their Id,
I'm thinking of Where so I would make something like this:
db.Books.Where(b => b.Id==1 || b.Id==3 || b.Id==5)
but if I have a long list of Id, or if I want to search by Title , it will be very painful code,
so is there a way to retrieve a list of items based on a group of values (like SQL: WHERE id IN..)
string[] bookNames = { "BookName1", "BookName2" };
db.Books.Where(b => bookNames.Contains(b.Name));
The solutions listed above all work - Dispersia's LINQ query's really nice actually.
One more possibility to keep in mind for what it's worth: you can always write your own LINQ-like extension methods. Here are a couple I put together for what they're worth. (I don't claim that these are actually better than the other solutions or that you'd necessarily want to use them instead - they're just something to keep in mind for reference in case you want to do something similar in the future).
Note that the compiler'll even allow you to add them to the System.Linq namespace if you want, but you could definitely argue about whether that's a good practice or not.
namespace System.Linq
{
public static class LinqExtensions
{
// This one's more or less like "Contains" except for the "params" part
// Example: book.Id.In(1, 2, 3, 4, 5)
public static bool In<T>(this T item, params T[] list)
{
foreach (T args in list)
{
if (args.Equals(item))
{
return true;
}
}
return false;
}
// Same idea as above except using an equality tester
// Example: listBooks.Where(book => book.In((bk, id) => bk.Id == id, 1, 2, 3, 4, 5));
public static bool In<T, U>(this T item, Func<T, U, bool> equalitytester, params U[] list)
{
foreach (U arg in list)
{
if (equalitytester(item, arg))
{
return true;
}
}
return false;
}
// See if any item in the first list is also in the second list
public static bool In<T, U>(this IEnumerable<T> list, Func<T, U, bool> equalityTester, params U[] argList)
{
foreach (T item in list)
{
foreach (U arg in argList)
{
if (equalityTester(item, arg))
{
return true;
}
}
}
return false;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With