[英]How to remove item from an anonymous list
在EF 4 C#上工作。我有一個匿名列表。想從匿名列表中刪除項目
Anonymous list :
var temp=from p in contex.students select p;//it’s a complex query,for now just use simple select
foreach(var item in temp)
{
if(item.StudentID)//if satisfy some condition then want to remove this student information from anonymous list
{
temp=temp.where(p=>studentID!=item.studentID);
}
}
上面的語法對我不起作用。我只是想在幾種情況下刪除項目。需要幫助如何從匿名列表中刪除項目。
如果有任何查詢,請高級。
您不應該從列表中刪除項目,因為這樣做會使foreach
循環的迭代器無效。 您可以無循環地做您想做的事情:
var temp = contex.students.Where(item => !CheckCondition(item.StudentID));
回想一下, Where
可讓您對整個集合進行整體操作。 將在每個學生ID上調用CheckCondition
(我嘗試按照您的示例;您不必僅根據StudentID
進行選擇),所有通過CheckCondition
學生都將被刪除。
請注意,如果contex
是EF / LINQ2SQL上下文,則在使用C#代碼檢查條件之前,需要添加AsEnumerable()
:
var temp = contex.students
.AsEnumerable()
.Where(item => !CheckCondition(item.StudentID));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.