LINQ JOIN直接指向对象

本文关键字:对象 JOIN LINQ | 更新日期: 2023-09-27 18:25:39

我是LINQ的新手,我实现了一个执行联接的LINQ语句,然后我得到查询的结果,迭代结果,将每个结果分配给一个新对象,然后将对象添加到对象列表中。有没有一种更优雅的方法来完成以下操作,让我直接选择对象列表?

感谢并非常感谢

        var clubAttendeeEducationList = new List<ClubAttendeeEducation>();

        var r = (from oer in db.OnlineEducationRegistrations
                join oec in db.OnlineEducationCourses on oer.OnlineEducationCourseId equals
                    oec.OnlineEducationCourseId
                where
                    (oer.MasterCustomerId.Equals(userId) && oer.DateCompleted >= start.Date &&
                     oer.DateCompleted <= upUntil.Date && oer.DateCompleted != null)
                select new {OnlineEducationRegistration = oer, oec.CourseTitle}).ToList();
        foreach (var item in r)
        {
            var educationItem = new ClubAttendeeEducation
                    {
                        Session = item.CourseTitle,
                        Date = item.OnlineEducationRegistration.DateCompleted.Value
                    };
            clubAttendeeEducationList.Add(educationItem);
        }

    return clubAttendeeEducationList;

LINQ JOIN直接指向对象

就像在查询中创建新的匿名对象一样,您可以创建任何类型的对象,并将结果转换为列表。

var clubAttendeeEducationList = (from oer in db.OnlineEducationRegistrations
                                /* rest of the query */
                                select new ClubAttendeeEducation
                                {
                                    Session = item.CourseTitle,
                                    Date = item.OnlineEducationRegistration.DateCompleted.Value
                                }).ToList();

如果您确实想要其他类型的对象,请不要选择匿名对象。只需直接在原始查询中选择实际想要的类型。