我正在尝试使用LINQ生成包含汇总值的类。
我有一个包含List的List。 我的返回应该是1个MasterClass对象,List包含值摘要。
MasterClass: Example data
public string A { get; set; } "1" "1" subclass(below)
public string B { get; set; } "1" "2" subclass(below)
public List<subClass> list { get; set; } "2" "3" subclass(below)
subClass: Example data(for each master)
public DateTime date { get; set; } 29/01/2018 10 5 20
public int NetChange { get; set; } 29/01/2018 20 10 30
public int Shares { get; set; } 30/01/2018 5 10 20
public int HeldPerc { get; set; } 31/01/2018 10 5 10
31/01/2018 10 5 20
31/01/2018 10 5 30
我想要的是得到所有具有master.A =“1”的子类的摘要。 (在这种情况下,2个大师类合并为一个计算按日期分组的子类的总值)
Master:(this part i can already achieve)
"1" "1/2" subclass(below)
subclass:(summed up values of both individual subclasses grouped by date)
29/01/2018 60 30 100
30/01/2018 10 20 40
31/01/2018 60 30 120
如何实现此计算
答案 0 :(得分:1)
如果我理解你的问题,那么你需要做的就是:
masterClassList
.Where(mc => mc.A == "1")
.SelectMany(mc => mc.SubClasses)
.GroupBy(sc => sc.Date)
.Select(g => new
{
Date = g.Key,
NetChange = g.Sum(sc => sc.NetChange),
Shares = g.Sum(sc => sc.Shares),
HeldPerc = g.Sum(sc => sc.HeldPerc),
});
以下是一个工作示例:https://dotnetfiddle.net/uO0Mxn。