how can we avoid a possible multiple enumeration warning?

One possible way to avoid enumerating the IEnumerable twice:

var redefineSchoolDatas = group.Select(g =>
{
    var elementsInGroup = g.ToList();
    return new RedefineSchoolData
    {
        ClassName = g.Key,
        Count = elementsInGroup.Count,
        Students = elementsInGroup.Select(s => new Student
        {
            StudentName = s.StudentName,
            StudentAge = s.StudentAge
        }).ToList(),
    }
}).ToList();

However, I would suggest you refrain from having a Count property in your RedefineSchoolData class. Maintaining a Count separate from the collection (Students) is not a good idea: imagine you delete a student – then you also need to remember to update the Count. Instead, you could build your class like so:

class RedefineSchoolData
{
    public Student Students { get; set; }
    public int Count => Students.Count;
    // Other properties kept out for brevity
}

// Now your LINQ statements could be:
var redefineSchoolDatas = group.Select(g =>
    new RedefineSchoolData
    {
        ClassName = g.Key,
        Students = g.Select(s => new Student
        {
            StudentName = s.StudentName,
            StudentAge = s.StudentAge
        }).ToList(),
    }).ToList();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top