【问题标题】:Filtering generic collection while comparing with another collection在与另一个集合进行比较时过滤通用集合
【发布时间】:2015-01-13 16:26:05
【问题描述】:

我必须在通用集合中进行一些过滤。我正在尝试为此使用 LINQ。这是我的代码:

from student in students
where student.ID == (Here is another collection) from newstudent in Newstudents
select newstudent.ID
select student 

我不知道如何将 int 集合与单个 int 进行比较。请告诉我一个好的方法。

【问题讨论】:

  • 那么您要进行什么比较?您是否要在该集合中查找所有具有 ID 的学生?如果是这样,您可以使用Contains,例如where ids.Contains(student.ID)... 或者您可以对集合使用连接。
  • 如果你有两个集合,你也可以使用 join
  • 我如何使用包含。我做不到。我已经更新了代码。请再看看我要做什么

标签: c# linq linq-to-entities filtering


【解决方案1】:

为了快速查找,首先将学生 ID 放入 HashSet。在那个上使用Contains来检查id的存在。

var studentIds = new HashSet<int>(newStudents.Select(x => x.ID));
var filtered = students.Where(x => studentIds.Contains(x.ID));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多