views:

157

answers:

5

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

+6  A: 
items = items.Where( x => !IsNotWhatINeed(x) );
Fyodor Soikin
I'd like to add that in LINQ, as with all functional code, it's more preferable to get a new list from old ones by applying a filter instead of making changes to it.
chakrit
+5  A: 

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.

Anthony Pegram
With such an optimistic and positive function, you can also write `items.Where(IsWhatINeed)`.
Kobi
thank you Anthony and Kobi
+2  A: 
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));
tylerl
A: 

Try This:

var items = YourDataContext.Items.Where(x => x.Container.ID == myContainerId 
    && !IsNotWhatYouNeed(x));
Johnny
+1  A: 

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.

jeroenh
Thanks jeroenh, could you explain or give me an example what Linq2Sql query is and what Linq2sql understands please? Thanks!