繁体   English   中英

将 lambda 表达式转换为 linq c#

[英]Convert lambda expression into linq c#

我有学生名单和讲师名单,我用双 foreach 语句编写了代码。

有没有办法使用 Lambda 表达式来简化此代码?

public void GetLecturersWorkloadStatistics(List<Student> studentList, List<Lecturer> lecturerList)
{
    foreach (Lecturer lecturer in lecturerList)
    {
        foreach (Student student in studentList)
        {
            if (lecturer.ModuleName == student.ModuleName && lecturer.LastName == student.LecturerLastName &&
                lecturer.FirstName == student.LecturerFirstName)
            {
                lecturer.Credits = lecturer.Credits + lecturer.ModuleValueInCredits;
            }
        }
    }
}

我认为您尝试的示例不起作用,因为它返回一个IEnumerable<Student>而您的方法应该返回一个List<Student>

您还缺少将&&子句组合在一起所需的一些括号,因此它们由||分隔操作员。

解决此问题的一种方法是将方法的返回类型更改为IEnumerable<Student> ,并在&&子句周围添加一些括号:

public IEnumerable<Student> GetStudentBySelectedLecturer(List<Student> linkedList,
    string text)
{
    var lecturerInformation = text.Split(' ');

    return from stud in linkedList
        where (stud.LecturerFirstName == lecturerInformation[0] &&
                stud.LecturerLastName == lecturerInformation[1]) ||
                (stud.LecturerFirstName == lecturerInformation[1] &&
                stud.LecturerLastName == lecturerInformation[0])
        select stud;
}

另一种方法是将返回值转换为List<Student>

public List<Student> GetStudentBySelectedLecturer(List<Student> linkedList,
    string text)
{
    var lecturerInformation = text.Split(' ');

    return (from stud in linkedList
        where (stud.LecturerFirstName == lecturerInformation[0] &&
               stud.LecturerLastName == lecturerInformation[1]) ||
              (stud.LecturerFirstName == lecturerInformation[1] &&
               stud.LecturerLastName == lecturerInformation[0])
        select stud).ToList();
}

当然,仍然存在一些潜在的问题,例如如果linkedListlecturernull ,或者text没有空格(尝试访问索引1时会得到IndexOutOfRangeException )。 此外,您可以在讲师姓名数组上使用Contains方法来简化您的where条件:

您可以通过执行以下操作来解决这些问题:

public IEnumerable<Student> GetStudentBySelectedLecturer(List<Student> students,
    string lecturer)
{
    if (students == null || lecturer == null) return null;

    var lecturerName = lecturer.Split(' ');

    return from student in students
        where lecturerName.Contains(student.LecturerFirstName) &&
              lecturerName.Contains(student.LecturerLastName)
        select student;
}

这与您的问题的输出完全相同,仅使用 lambda 表达式。

    studentListBySelectedLecturer = (from stud in linkedList
              where stud.LecturerFirstName == lecturerInformation[0] &&
              stud.LecturerLastName == lecturerInformation[1] ||
              stud.LecturerFirstName == lecturerInformation[1] &&
              stud.LecturerLastName == lecturerInformation[0]
              select stud).ToList();

    return studentListBySelectedLecturer;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM