[英]c# linq, sum distinct values by index
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.. 因此,我有“ p”类作为列表。.“ p”类中的某些名称将相同,而有些不同。
I need to sum the values in "ip" by index for only the class "p" that has the same name.. 我只需要对具有相同名称的类“ p”按索引求和“ ip”中的值。
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
: 可以使用
SelectMany
和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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.