[英]LINQ: How to remove element from IQueryable<T>
How do you loop through IQueryable and remove some elements I don't need. 你如何循环IQueryable并删除一些我不需要的元素。
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
提前致谢
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. 这(负)是什么
not
经营人。
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. 其他答案是正确的,您可以使用'where'语句进一步细化查询。 However, I'm assuming your query is a Linq2Sql query.
但是,我假设您的查询是Linq2Sql查询。 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. 如果你真的想扩展IQueryable,那么'IsNotWhatINeed'函数必须转换为Linq2Sql理解的东西。
Try This: 试试这个:
var items = YourDataContext.Items.Where(x => x.Container.ID == myContainerId
&& !IsNotWhatYouNeed(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.