Using Contains () in a LINQ Query

I am using this piece of code to get the desired list of rows from a table:

_userObjectSet = EntityFrameWorkContext.CreateObjectSet<User>();
List<int> selectedUserIDs = Method(); //Returns a specific set of int user IDs...
var results = _userObjectSet.Where(c => selectedUserIDs.Contains(c.ID)).ToList();

      

This works like "results", will only contain records whose id field matches the item in the selectedUserIDs list.

The problem is that if I look at the Windows Task Manager, LINQ seems to load ALL the row in the THEN table, filtering them out. This table has a huge number of rows, and pretty soon the process is over 1GB, which I don't really like.

I can also tell that it does it because of the time it takes to complete.

Is there a way to tell LINQ to generate a query that looks like this:

SELECT * FROM Users WHERE ID IN (34,55,66,77, etc.)

      

which will only return the exact strings I'm looking for and use less memory?

Thank!

+3


source to share


2 answers


Try to join .. I think you can tell the difference ...



List<int> selectedUserIDs = Method(); //Returns a specific set of int user IDs...
var results = (from u in _userObjectSet 
               join id in selectedUserIDs on u.Id equals id
               select u);

      

0


source


You will need something like LinqKit for this . In particular, take a look at the PredicateBuilder that comes with the kit, as I think you need this to fix your problem.



-1


source







All Articles