代码之家  ›  专栏  ›  技术社区  ›  user584018

如何避免可能的多重枚举警告

c#
  •  0
  • user584018  · 技术社区  · 4 年前

    下面这段代码我得到警告 possible multiple enumeration Count g.ToList() 为了 Students g.Select

    如何避免呢?

     var redefineSchoolDatas = group.Select(g => new RedefineSchoolData
            {
                ClassName = g.Key,
                Count = g.ToList().Count,
                Students = g.Select(s => new Student
                {
                    StudentName = s.StudentName,
                    StudentAge = s.StudentAge
                }).ToList(),
            }).ToList();
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Xerillio    4 年前

    IEnumerable 两次:

    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();
    

    不过,我建议你不要 Count RedefineSchoolData 班级。维护 计数 与收藏分开( Students )不是个好主意:假设你删除了一个学生-那么你还需要记住更新 计数

    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();