Aximili
Aximili

Reputation: 29484

LINQ: How to remove element from IQueryable<T>

How do you loop through IQueryable and remove some elements I don't need.

I am looking for something like this

var items = MyDataContext.Items.Where(x => x.Container.ID == myContainerId);
foreach(Item item in items)
{
  if(IsNotWhatINeed(item))
    items.Remove(item); 
}

Is it possible? Thanks in advance

Upvotes: 16

Views: 30145

Answers (5)

jeroenh
jeroenh

Reputation: 26792

The other answers are correct in that you can further refine the query with a 'where' statement. However, I'm assuming your query is a Linq2Sql query. So you need to make sure you have the data in memory before further filtering with a custom function:

var items = MyDataContext.Items.Where(x => x.Container.ID == myContainerId)
    .ToList(); // fetch the data in memory

var itemsToRemove = items.Where(IsNotWhatINeed);

If you really want to extend the IQueryable, then the 'IsNotWhatINeed' function must be translated to something that Linq2Sql understands.

Upvotes: 2

Johnny
Johnny

Reputation: 1575

Try This:

var items = YourDataContext.Items.Where(x => x.Container.ID == myContainerId 
    && !IsNotWhatYouNeed(x));

Upvotes: 1

tylerl
tylerl

Reputation: 30867

var items = MyDataContext.Items.Where(x => x.Container.ID == myContainerId 
    && !IsNotWhatINeed(x));

or

var items = MyDataContext.Items.Where(x => x.Container.ID == myContainerId) 
    .Where(x=> !IsNotWhatINeed(x));

Upvotes: 3

Anthony Pegram
Anthony Pegram

Reputation: 126942

You should be able to query that further as in this

var filtered = items.Where(itm => IsWhatINeed(itm));

Also notice the subtle change in the boolean function to an affirmative rather than a negative. That (the negative) is what the not operator is for.

Upvotes: 18

Fyodor Soikin
Fyodor Soikin

Reputation: 80805

items = items.Where( x => !IsNotWhatINeed(x) );

Upvotes: 10

Related Questions