如何从匿名列表中删除项目

时间:2013-09-04 15:53:20

标签: c# linq entity-framework anonymous-function

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

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

如果有任何查询,请先询问。谢谢。

1 个答案:

答案 0 :(得分:3)

您不应该随便从列表中删除项目,因为这样做会使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));
相关问题