A
A
Alexander Shapovalov2015-03-01 14:01:32
.NET
Alexander Shapovalov, 2015-03-01 14:01:32

How to find records corresponding to array elements without resorting to a loop, and using a lambda expression?

Hello, the question is how to find all the database elements corresponding to the values ​​from the array without using a loop.
For example, an array, you need to find in all records the corresponding elements of this array from a table with books. You can of course use a list, adding elements to it as you find it, just by using a loop that iterates through the elements of the array and outputs its values. Whether but me interests it is possible to make selection by one request having written a lambda expression. Thanks in advance for the answers . It turned out to be a request of this kind:
int[] bookTypes = {1, 2, 6, 8};

var books = db.Books.Where(a=> bookTypes.Contains(a.TypeId));

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mayorovp, 2015-03-01
@shapovalov_org

Use the Linq Where and Contains extension methods. You can also use the IndexOf method to find an element in an array.

A
asdz, 2015-03-01
@asdz

It is possible, the query expression depends on what you are looking for, where, and what search conditions.

A
Alexander Shapovalov, 2015-03-01
@shapovalov_org

For example, find all books whose type matches the values ​​from the arrays. I didn’t find examples on the Internet for a similar case, it’s easy to select one element at a time

var books = dc.Books.Where(a => a.Status == true && a.TypeId==bookTypes[i]);

But how to write a lambda expression to search not for one element, but for all at once?
Will this help:
var books = dc.Books.Where(a => a.Status == true && bookTypes.Equals(a.TypeId));
???

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question