LINQ: How to remove element from IQueryable<T>

纵饮孤独 提交于 2019-12-01 15:12:31

问题


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


回答1:


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.




回答2:


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



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



回答4:


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.




回答5:


Try This:

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


来源:https://stackoverflow.com/questions/2937528/linq-how-to-remove-element-from-iqueryablet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!