将lambda表达式转换为linq c#

时间:2018-05-21 19:26:53

标签: c# linq lambda

所以我用foreach编写了这段代码,我应该使用linq声明编程。我的问题是,它应该在linq中看起来如何?我有几个例子,但在我的情况下它们没用了

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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

我认为您尝试的示例不起作用,因为它返回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中没有空格(你会得到一个)尝试访问索引IndexOutOfRangeException1。此外,您可以在讲师姓名数组上使用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;
}

答案 1 :(得分:0)

现在可以使用,我使用了这段代码。

    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;