我创建了一个名为Impacts的类:
public class Impacts {
public Impacts(string _Source, int _Number, string _Target) {
this.Source = _Source;
this.Number = _Number;
this.Target = _Target;
}
}
并创建了这个类的列表:
List<Impacts> ListOfImpacts = new List<Impacts>();
然后,我在创建的列表中添加了项目:
ListOfImpacts.Add(new Impacts("a" , 1 , "b")); //record 1
ListOfImpacts.Add(new Impacts("c" , 1 , "d")); //record 2
ListOfImpacts.Add(new Impacts("d" , 1 , "a")); //record 3
ListOfImpacts.Add(new Impacts("d" , 1 , "a")); //record 4
ListOfImpacts.Add(new Impacts("d" , 1 , "a")); //record 5
我想将记录3和记录4和记录5结合起来,因为它们具有相同的“Source”=“d”和相同的“Target”=“a”,所以我可以:
new Impacts("d", 3 , "a"); // 3 is the number of iterations of this record
并删除三个重复的记录。
有人可以帮助我吗?
答案 0 :(得分:7)
var newList = ListOfImpacts.GroupBy(g => new {g.Source, g.Target})
.Select(g => new Impacts(g.Key.Source, g.Count(), g.Key.Target))
.ToList();
答案 1 :(得分:2)
var newList = ListOfImpacts
.GroupBy(i => new { i.Source, i.Target })
.Select(i => new Impacts(i.Key.Source, i.Sum(x => x.Number), i.Key.Target))
.ToList();