Question : What's the fastest way to do a wherein query in linq2sql

I have a database table containing many hundred's of thousands of rows and I'm try to get those rows whose ID's match with those of another subset of several thousands of ID's.

I have an IQueryable that returns the rows and then I'm doing a linq select as follows:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
string[] unitIDs = { AAAAAAA", "AAAAAAB" };

var unitEvents = systemRepository.GetUnitEvents();

var matches = from a in unitEvents
			  from b in unitIDs
			  where a.UnitID == b
			  select new { a, b };

int count = matches.Count();


(The above example only matches 2 unitID's but this could be many thousands).

Although the above works, it can take several seconds for it to finish the matches.Count() statement. If I do a similar SQL statement directly via SQL it returns in less than a second. e.g.

select * from unit_event where unitid in ("AAAAAAA", "AAAAAAB")

I am not experienced with Linq/Sql and wanted to know if I am using the best method.

Perhaps I should write a stored procedure to keep it all in the database?

Many thanks

Answer : What's the fastest way to do a wherein query in linq2sql

Hi Petroclus;

In order to do a IN clause in the EF first release you will need to download the LinqKit which is free to use which will build a predicate so that it can be used in the query.

Download LinqKit from here at the bottom of page ==>  http://www.albahari.com/nutshell/linqkit.aspx
Unzip the file and open the solution in Visual Studio and set the Solution to Release.
Compile the solution. If no errors close the solution.
Now in your current project add a reference to the LinqKit.dll which will be in the bin/release directory of LinqKit project.
Add the using statement to your project ==>  using LinqKit;
The below function and query should work not.

The following link is info on LinqKet.
Dynamically Composing Expression Predicates
http://www.albahari.com/nutshell/predicatebuilder.aspx

Fernando
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
public IEnumerable<UnitEvent> GetUnitEventsWhereUnitIDIn(string[] unitIDs)
{
    var predicate = PredicateBuilder.False<UnitEvent>();
    foreach (string unitID in unitIDs)
    {
        string id = unitID;
        predicate = predicate.Or(I => I.UnitID.Contains(id));
    }

    return db.UnitEvents.AsExpandable().Where(predicate);
}
Random Solutions  
 
programming4us programming4us