C# LINQ 根据List中对象的某一个字段分组拼接

  • Post author:
  • Post category:其他


实验数据

#region data
protected enum GradeLevel { FirstYear = 1, SecondYear, ThirdYear, FourthYear };
protected class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public GradeLevel Year;
    public List<int> ExamScores;
}

protected static List<Student> students = new List<Student>
{
    new Student {FirstName = "Terry", LastName = "Adams", ID = 120,
        Year = GradeLevel.SecondYear,
        ExamScores = new List<int>{ 99, 82, 81, 79},
        ClassID = 2},
    new Student {FirstName = "Cesar", LastName = "Garcia", ID = 114,
        Year = GradeLevel.ThirdYear,
        ExamScores = new List<int>{ 97, 89, 85, 82},
        ClassID = 4},
    new Student {FirstName = "Debra", LastName = "Garcia", ID = 115,
        Year = GradeLevel.ThirdYear,
        ExamScores = new List<int>{ 35, 72, 91, 70},
        ClassID = 3},
    new Student {FirstName = "Hugo", LastName = "Garcia", ID = 118,
        Year = GradeLevel.SecondYear,
        ExamScores = new List<int>{ 92, 90, 83, 78},
        ClassID = 2},
    new Student {FirstName = "Lance", LastName = "Tucker", ID = 119,
        Year = GradeLevel.ThirdYear,
        ExamScores = new List<int>{ 68, 79, 88, 92},
        ClassID = 3},
    new Student {FirstName = "Michael", LastName = "Tucker", ID = 122,
        Year = GradeLevel.FirstYear,
        ExamScores = new List<int>{ 94, 92, 91, 91},
        ClassID = 1},
    new Student {FirstName = "Eugene", LastName = "Zabokritski", ID = 121,
        Year = GradeLevel.FourthYear,
        ExamScores = new List<int>{ 96, 85, 91, 60},
        ClassID = 4}
};
#endregion

解决代码

private static void PracticeLINQ()
{
    var studentJson =
        from student in students
        where student.LastName == "Garcia"
        group student by new { student.Year, student.LastName } into newGroup
        let firstList = from newStu in newGroup select newStu.FirstName
        select new { year = newGroup.Key.Year, last = newGroup.Key.LastName, first = string.Join(",", firstList) };
    Console.WriteLine(JsonConvert.SerializeObject(studentJson));
}



版权声明:本文为zhao502063335原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。