首页 > 编程语言 >C# List合并相同元素

C# List合并相同元素

时间:2022-11-30 19:00:10浏览次数:37  
标签:Name C# 元素 List Sex Course Score Student new

  •  C# List合并相同元素,对相同属性的列进行求和

原数据

合并后

 

 

 

 

 
public class Student
{
    public string? Name { get; set; }
    public string? Sex { get; set; }
    public int Score { get; set; }//成绩
    public string? Course { get; set; }//课程
}

//数据源
List<Student> students = new List<Student>
{
    new Student(){Name="刘一",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="陈二",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="张三",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="张三",Sex="男",Score=1 ,Course="数学"},//重复行3
    new Student(){Name="张三",Sex="男",Score=1 ,Course="音乐"},//重复行3
    new Student(){Name="李四",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="刘一",Sex="男",Score=1 ,Course="美术"},//重复行1
    new Student(){Name="王五",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="赵六",Sex="男",Score=1 ,Course="语文"},
    new Student(){Name="张三",Sex="男",Score=1 ,Course="化学"}//重复行3
};

List<Student> result = new List<Student>();
while (students.Count > 0)
{
    Student stu = students[0];
    students.RemoveAt(0);//移除元素

    List<Student> list = new List<Student>();//创建临时列表
    foreach (var item in students)
    {
        if (item.Name.Equals(stu.Name))
        {
            stu.Score += item.Score;
            stu.Course += " "+item.Course;
        }
        else
        {
            list.Add(item);
        }
    }
    students = list;
    result.Add(stu);
}

foreach (var item in result)
{
    Console.WriteLine(item.Name +"丨"+item.Sex + "丨" + item.Score + "丨" + item.Course);
}

标签:Name,C#,元素,List,Sex,Course,Score,Student,new
From: https://www.cnblogs.com/lxiamul/p/16938713.html

相关文章