I have multiple List with multiple values that may or may not have the same number of items.. I need to add up only the numbers for a distinct name by index..
heres some code to help explain...
public static List<p> pList= new List<p>();
public class p
{
public string name;
public double sum;
public List<double> ip;
}
So, I have class "p", as a list.. some of the names in class "p" will be same and some different..
I need to sum the values in "ip" by index for only the class "p" that has the same name..
Data Example..
name = a, sum = 10, ip = {2,2,2,2,2}
name = a, sum = 10, ip = {0,0,5,5}
name = a, sum = 5, ip = {0,0,5}
name = b, sum = 20, ip = {0,20}
name = b, sum = 10, ip = {10}
Result..
name = a, sum = 25, ip = {2,2,12,7,2}
name = b, sum = 30, ip = {10,20}
Below is the code I have already written..
List<p> distinctmerge = pList
.GroupBy(t => t.name)
.Select(g => new p
{
name = g.Select(a => a.name).FirstOrDefault(),
sum = g.Sum(a => a.sum),
ip = new List<double>() { 1, 2, 3 }
}).ToList();
The part I cant figure out is here..
ip = new List<double>() { 1, 2, 3 }
您可以通过以下方式总结IP列表:
ip = Enumerable.Range(0, g.Select(a => a.ip.Length).Max()).Select(idx => g.Select(a => a.ip.ElementAtOrDefault(idx)).Sum()).ToList()
It can be done using SelectMany
and GroupBy
:
List<p> distinctmerge = pList
.GroupBy(t => t.name)
.Select(g => new p
{
name = g.Select(a => a.name).FirstOrDefault(),
sum = g.Sum(a => a.sum),
ip = g.SelectMany(a => a.ip.Select((e, i) => new { e, i }))
.GroupBy(a => a.i)
.OrderBy(a => a.Key)
.Select(a => a.Sum(e => e.e))
.ToList()
}).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.