[英]How to combine many list items into one item?
I have created a class named Impacts: 我创建了一个名为Impacts的类:
public class Impacts {
public Impacts(string _Source, int _Number, string _Target) {
this.Source = _Source;
this.Number = _Number;
this.Target = _Target;
}
}
And have created a list of this class: 并创建了这个类的列表:
List<Impacts> ListOfImpacts = new List<Impacts>();
And then, I have added items to the list created: 然后,我在创建的列表中添加了项目:
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
I want to combine record 3 and record 4 and record 5 since they have the same "Source"="d" and same "Target"="a", so I could have: 我想把记录3和记录4和记录5结合起来,因为它们具有相同的“Source”=“d”和相同的“Target”=“a”,所以我可以:
new Impacts("d", 3 , "a"); // 3 is the number of iterations of this record
and delete the three repeated records. 并删除三个重复的记录。
Can someone help me? 有人能帮我吗?
var newList = ListOfImpacts.GroupBy(g => new {g.Source, g.Target})
.Select(g => new Impacts(g.Key.Source, g.Count(), g.Key.Target))
.ToList();
Live example: http://rextester.com/XOIYM52525 实例: http : //rextester.com/XOIYM52525
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.