I have the following code:
var studentClassAttendancesGrouped =
classAttendanceByCriteria.OrderBy(x => x.Lecture.Id).GroupBy(x => new { x.Lecture, x.Teacher });
I am trying to return studentClassAttendancesGrouped
from a method.But I can not determine the return type of the method.
This overload of the GroupBy
will return IEnumerable<IGrouping<TKey, TSource>>
as seen from the source code.
You just need to project your enumerable with the Select()
and of course you must call ToList()
at the end to execute the query and create a list:
var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
.GroupBy(x => new { x.Lecture, x.Teacher })
.Select(x => new {x.Key.Lecture, x.Key.Teacher})
.ToList();
But, the above code creates a list of the anonymous types. If you are going to return the above statement from the method, then you need to use or to create a custom object and return the list of this:
public class LectureTeacher
{
public string Lecture { get; set; }
public string Teacher { get; set; }
}
public List<LectureTeacher> GetDogsWithBreedNames()
{
var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
.GroupBy(x => new { x.Lecture, x.Teacher })
.Select(x => new LectureTeacher {Lecture = x.Key.Lecture, Teacher = x.Key.Teacher})
.ToList();
return res;
}
By the way, GroupBy
has several other overloads which you can specify result selector and it will return IEnumerable
to you:
myList.OrderBy(x => x.Lecture.Id)
.GroupBy(x => new { x.Lecture, x.Teacher } //key selector
key => new LectureTeacher // result selector
{
Lecture = key.Lecture,
Teacher = key.Teacher
})
.ToList();
I would suggest you to create a custom class and return it from your method:-
IEnumerable<CustomType> studentClassAttendancesGrouped =
classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
.GroupBy(x => new { x.Lecture, x.Teacher })
.Select(x => new CustomType { Lecture = x.Key.Lecture, Teacher = x.Key.Teacher });
Where, CustomType
will look something like this:-
public class CustomType
{
public string Lecture {get; set; }
public string Teacher {get; set; }
}
You can add more columns as per your need and finally return IEnumerable<CustomType>
from your method.
Thus, your method will look like:-
public IEnumerable<CustomType> MyMethod()
{
return classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
.GroupBy(x => new { x.Lecture, x.Teacher })
.Select(x => new CustomType { Lecture = x.Key.Lecture, Teacher = x.Key.Teacher });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With