分组时如何为学生列表分配值

时间:2020-10-28 16:22:03

标签: c# linq

我有一个简单的数据列表,

List<SchoolData> schoolData = new List<SchoolData>
        {
            new SchoolData{ClassName = "A", StudentName = "abc", StudentAge = 1},
            new SchoolData{ClassName = "A", StudentName = "xyz", StudentAge = 2},
            new SchoolData{ClassName = "B", StudentName = "pqr", StudentAge = 10},
            new SchoolData{ClassName = "B", StudentName = "lmn", StudentAge = 11},
        };

在这里,我需要按ClassName对数据进行分组并像这样排列数据,

var d = new List<RedefineSchoolData>()
        {
            new RedefineSchoolData{ClassName = "A", Students = new List<Student>
            {
                new Student{StudentName = "abc", StudentAge = 1},
                new Student{StudentName = "xyz", StudentAge = 2}
            }}
        };

我正在尝试这样做,但是如何填写Students

var group = schoolData.GroupBy(x => x.ClassName);

        foreach (var g in group)
        {
            redefineSchoolDatas.Add(new RedefineSchoolData
            {
                ClassName = g.Key,
                Students = g.ToList() //how to convert
            });
        }

这里是所有的类结构,

 public class SchoolData
    {
        public string ClassName { get; set; }
        public string StudentName { get; set; }
        public int StudentAge { get; set; }
    }

    public class RedefineSchoolData
    {
        public string ClassName { get; set; }
        public List<Student> Students { get; set; }
    }

    public class Student
    {
        public string StudentName { get; set; }
        public int StudentAge { get; set; }
    }

2 个答案:

答案 0 :(得分:2)

您可以在GroupBy中进行所有操作:

var newList = schoolData
    .GroupBy(
        x => x.ClassName,
        (k,v) => new RedefineSchoolData(){
            ClassName=k,
            Students=v.Select(s => new Student(){
                StudentName=s.StudentName,
                StudentAge=s.StudentAge
                }).ToList()
        })
    .ToList();

答案 1 :(得分:1)

您需要执行以下代码以获取Student属性:

Students = g.Select(s => new Student
{
    StudentName = s.StudentName,
    StudentAge = s.StudentAge
}).ToList()

您也可以将foreach替换为:

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