markzzz
markzzz

Reputation: 47945

How can I concatenate a where clause using OR on LINQ?

I have this code :

foreach (Package pack in Packages)
{
    filteredResults = filteredResults.Where(o => o.ID == pack.ID);
}

the only problems is that I filter the result N time (so N where). What I'd like to do is to filter the result only one time (only a where clause) with N expression. Somethings like :

    Where o.ID == pack.ID OR o.ID == pack.ID OR o.ID == pack.ID OR o.ID == pack.ID...

Is it possible to do this with LINQ?

Upvotes: 2

Views: 2903

Answers (5)

Matteo1010
Matteo1010

Reputation: 361

I think you need to use expression with LinqKit

var v = from utente in db.Utente
        select utente;

Expression<Func<Utente, bool>> expr = c => c.Age == 26;
expr = expr.Or<Utente>(c => c.Name != "Matteo");

v = v.Where(expr.Expand());

The result is:

SELECT...... FROM......
WHERE (26 = [Extent1].[Age ]) OR ('Matteo' <> [Extent1].[Name])

I have the same issue, i try this solution

Upvotes: 1

Aidan
Aidan

Reputation: 4891

Do you not want Intersect()? i.e

var ids = filteredResults.Select( fr => fr.Id ).Intersect(Packages.Select( p => p.PackID ) )  ;

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28824

var packIds = Packages.Select(x=>x.ID).ToArray();
filteredResults = filteredResults.Where(o=> packIds.Contains(o.ID));

If this is linq to sql this will get translated into:

WHERE ID IN (1,2,3,4)

Upvotes: 3

Sven
Sven

Reputation: 22673

Something like this might help you:

filteredResults = originalResults.Where(o => Packages.Any(p => p.ID == o.ID));

Upvotes: 2

DoctorMick
DoctorMick

Reputation: 6793

Something like the code below should work, or at least steer you in the right direction.

-- Get all the package IDs you want to select on.
var packIDs = from pack in Packages
    select pack.ID;

-- Return all results where the ID is in the package ids above.
filteredResults = from result in filteredResults
    where packIDs.Contains(result.ID)
    select result;

The above assumes your and's were a logic mistake and you meant ors.

Upvotes: 3

Related Questions