2

使用 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);
    }
    }

上面的语法对我不起作用。我只想根据几个条件删除项目。需要帮助如何从匿名列表中删除项目。

如果有任何疑问请提前询问。谢谢。

4

1 回答 1

3

You should not be removing items from the list as you go, because doing so invalidates the iterator of the foreach loop. You can do what you want without a loop:

var temp = contex.students.Where(item => !CheckCondition(item.StudentID));

Recall that Where lets you operate on the entire collection as a whole. The CheckCondition would be called on every student ID (I tried to follow your example; you do not need to base the selection solely on the StudentID), and all students who pass CheckCondition would be removed.

Note that if contex is an EF/LINQ2SQL context, you would need to add AsEnumerable() before checking conditions using your C# code:

var temp = contex.students
    .AsEnumerable()
    .Where(item => !CheckCondition(item.StudentID));
于 2013-09-04T15:57:23.313 回答