开发者

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 someth开发者_如何学Going 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


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.


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


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));


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.


Try This:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜