【问题标题】:apply a collection of courses to a collection of students将一组课程应用于一组学生
【发布时间】:2015-01-05 11:05:55
【问题描述】:

我正在处理对象集合,并试图摆脱遇到问题时循环的习惯,并查看 API 是否已经提供。

我目前有一组学生和一组学生正在学习的课程。这些课程有一个学生 ID,所以我可以编写一个大的旧 for 循环,围绕学生循环,为每个学生找出课程并将它们插入。

Dim Students As Generic.List(Of Student)
Dim Courses As Generic.List(Of Course)

For Each s As Student In Students
    s.Courses = Courses.Where(x => x.StudentId == s.StudentId)
Next

我想知道 linq 是否以某种形式涵盖了此功能。我正在寻找这样的东西:

Students.*DoSomethingClever(Courses, x => x.StudentId)*

我知道上面的内容可能看起来很废话,但我希望它传达了我想要实现的目标。

亚历克斯

【问题讨论】:

  • 您正在寻找的功能称为:join。

标签: c# .net linq collections


【解决方案1】:

你可以做类似的事情

Students.ForEach(s => s.Courses = Courses.Where(x => x.StudentId == s.StudentId));

您可以并行执行此操作(仅适用于大型集合并且仅当您至少有两个处理器内核时)

Students.AsParallel().ForAll(s=>
{
    s.Courses = Courses.Where(x => x.StudentId == s.StudentId));
});

【讨论】:

  • 看起来真不错!有什么方法可以在 linq Students = From s as Student in Students 风格中表达这一点?在这个过程中,我有一种风格。对不起,如果这有点厚脸皮!
  • 是的,你可以使用from student in Students.AsParallel() where...
  • 酷,我现在就试试!
【解决方案2】:

如果说 DoSomethingClever 是指加入课程中的数据,请参阅:

Dim JoinedData = From s In Students
                    Join c In Courses
                    On s.StudentId Equals c.StudentId
                    Select StudentName = s.FirstName, CourseName = c.Name

更多信息:How to: Combine Data with LINQ by Using Joins (Visual Basic)

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    相关资源
    最近更新 更多