-
有只小跳蛙
你可以很容易地使用 Linq 做到这一点假设您的 Animal Type 声明为public class Animal{public string Name {get;set;}public int Age{get;set;}public string Gender {get;set;}}您可以按名称对重复项进行分组并计算年龄总和。var list = new List<Animal>{ new Animal{Name="Ant",Age=9,Gender="M"}, new Animal{Name="Ant",Age=2,Gender="M"}, new Animal{Name="Lion",Age=8,Gender="M"}, new Animal{Name="Pig",Age=1,Gender="F"}, }; list.AddRange( list.GroupBy(x=>x.Name) .Where(x=>x.Count()>1) .Select(x=> new Animal{Name = x.First().Name, Gender= x.First().Gender, Age = x.Sum(c=>c.Age)}));输出Name Age GenderAnt 9 M Ant 2 M Lion 8 M Pig 1 F Ant 11 M
-
大话西游666
var animals = new List<Animal>{ new Animal { Name = "Ant", Age = 9, Gender = "M"}, new Animal { Name = "Ant", Age = 2, Gender = "M"}, new Animal { Name = "Lion", Age = 8, Gender = "M"}, new Animal { Name = "PIG", Age = 1, Gender = "F"},};var new_animals = from animal in animals group animal by animal.Name into grp where grp.Count() >= 2 select new Animal { Name = grp.Key, Age = grp.Sum(a => a.Age), Gender = "M" };animals.AddRange(new_animals);foreach(var animal in animals){ WriteLine(animal);}
-
holdtom
您的代码会覆盖现有的动物,因为您没有为总数创建新的动物new Animal()。在重复项下方的正确位置获取重复项总计非常棘手。为此,我将创建一个新类,Animal以便能够将动物与总数记录区分开来。class Animal{ public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; }}class AnimalTotals : Animal{}像这样创建重复的总计:var duplicateTotals = listAnimals .GroupBy(a => (a.Name, a.Gender)) .Where(g => g.Count() > 1) .Select(g => new AnimalTotals { Name = g.Key.Name, Age = g.Sum(a => a.Age), Gender = g.Key.Gender });请注意,我使用值元组(在 C# 7.0 中引入)来创建由名称和性别组成的组键。然后我将重复的总数与现有列表合并,并对结果进行排序以获得重复项下方的总数。listAnimals = listAnimals .Concat(duplicateTotals) .OrderBy(a => a.Name) .ThenBy(a => a.Gender) .ThenBy(a => a is AnimalTotals ? 1 : 0) .ToList();有了这个样本数据var listAnimals = new List<Animal> { new Animal{ Name="Ant", Age = 9, Gender = "M" }, new Animal{ Name="Ant", Age = 2, Gender = "M" }, new Animal{ Name="Ant", Age = 5, Gender = "F" }, new Animal{ Name="Ant", Age = 1, Gender = "F" }, new Animal{ Name="Lion", Age = 8, Gender = "M" }, new Animal{ Name="Pig", Age = 1, Gender = "F" },};的输出foreach (Animal a in listAnimals) { if (a is AnimalTotals) { Console.WriteLine($"{a.Name} {a.Gender} totals: {a.Age,4}"); } else { Console.WriteLine($"{a.Name,-6} {a.Age,2} {a.Gender}"); }}是Ant 5 FAnt 1 FAnt F totals: 6Ant 9 MAnt 2 MAnt M totals: 11Lion 8 MPig 1 F