16

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Aximili
  • 28,626
  • 56
  • 157
  • 216

5 Answers5

18

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
  • 123,721
  • 27
  • 225
  • 246
  • 2
    With such an optimistic and positive function, you can also write `items.Where(IsWhatINeed)`. – Kobi May 30 '10 at 09:58
  • 1
    The positive version of a function also eliminates the double negative scenario: `!IsNotWhatINeed()` – Adam Naylor Jan 15 '14 at 22:45
10
items = items.Where( x => !IsNotWhatINeed(x) );
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • 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 May 30 '10 at 12:21
3
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
  • 30,197
  • 13
  • 80
  • 113
2

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
  • 26,362
  • 10
  • 73
  • 104
  • Thanks jeroenh, could you explain or give me an example what Linq2Sql query is and what Linq2sql understands please? Thanks! – Aximili May 31 '10 at 12:21
1

Try This:

var items = YourDataContext.Items.Where(x => x.Container.ID == myContainerId 
    && !IsNotWhatYouNeed(x));
Johnny
  • 1,555
  • 3
  • 14
  • 23