C# List类型分组求和

        static void Main(string[] args)
        {           
            List personList = new List();
            Person p1 = new Person();
            p1.Name = "Bob";
            p1.Age = "14";           
            p1.Salary = 1200;
            personList.Add(p1);
            Person p2 = new Person();
            p2.Name = "Bob";
            p2.Age = "14";           
            p2.Salary = 1500;
            personList.Add(p2);
            Person p3 = new Person();
            p3.Name = "Ken";
            p3.Age = "56";        
            p3.Salary = 1000;
            personList.Add(p3);             
            var groupList = personList.GroupBy(m => new { m.Name, m.Age }).
                        Select(a => new
                        {
                            Name = a.Key.Name,
                            Salary = a.Sum(c=>c.Salary)
                        }).ToList();
            foreach (var item in groupList)
            {
                Console.WriteLine("Name:{0}--Salary:{1}", item.Name,item.Salary);
            }
            Console.ReadKey();
        }

 

你可能感兴趣的:(C#)