Reputation: 5832
I am rather new to LINQ and I have implemented a LINQ statement that does a join and then I get the results of the query, iterate through the results and assign each result to a new object and then add the object to a list of objects. Is there a more elegant way to do the following such that I am selecting right into the object list?
Thanks and much appreciated
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;
Upvotes: 0
Views: 104
Reputation: 203802
Don't select out an anonymous object if you actually want objects of another type. Simply select out the type that you actually want directly in your original query.
Upvotes: 0
Reputation: 56688
Just as you are creating new anonymous object in your query you can create object of any type you want, and turn result into list.
var clubAttendeeEducationList = (from oer in db.OnlineEducationRegistrations
/* rest of the query */
select new ClubAttendeeEducation
{
Session = item.CourseTitle,
Date = item.OnlineEducationRegistration.DateCompleted.Value
}).ToList();
Upvotes: 1