I have created a class named 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:
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
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.