我有多个List,其中包含多个值,可能有也可能没有相同数量的项目。 我需要通过索引只添加不同名称的数字..
下面是一些代码来帮助解释...
public static List<p> pList= new List<p>();
public class p
{
public string name;
public double sum;
public List<double> ip;
}
所以,我有班级“p”,作为一个清单.. “p”类中的一些名称会相同而且有些不同......
我需要通过索引将“ip”中的值仅与具有相同名称的类“p”相加。
数据示例..
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}
结果..
name = a, sum = 25, ip = {2,2,12,7,2}
name = b, sum = 30, ip = {10,20}
以下是我已编写的代码..
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();
我无法弄清楚的部分就在这里..
ip = new List<double>() { 1, 2, 3 }
答案 0 :(得分:3)
你可以通过
总结ip列表 ip = Enumerable.Range(0, g.Select(a => a.ip.Length).Max()).Select(idx => g.Select(a => a.ip.ElementAtOrDefault(idx)).Sum()).ToList()
答案 1 :(得分:2)
可以使用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();