这是我的课程:
class Account{
public List<AccountRecord> AccountRecords{set;get;}
}
class AccountRecord{
public IEnumerable<AccountValue> AccountValues{set;get;}
}
class AccountValue{
public int ID{set;get;}
public decimal value{set;get;}
}
我可以使用Entity Framework C#按ID获取AccountValue值组的总和 例如:
Data:
ID=1 value=5
ID=1 value=6
ID=2 value=7
ID=2 value=9
ID=3 value=2
Can I get this Result:
ID=1 Value=11
ID=2 value=16
ID=3 value=2
代码:
Account acc = new Account();
AccountRecord ar = new AccountRecord();
ar.AccountValues.Add(new AccountValue { ID = 1, value = 5 });
ar.AccountValues.Add(new AccountValue { ID = 1, value = 7 });
ar.AccountValues.Add(new AccountValue { ID = 2, value = 9 });
ar.AccountValues.Add(new AccountValue { ID = 2, value = 6 });
ar.AccountValues.Add(new AccountValue { ID = 3, value = 2 });
AccountRecord ar1 = new AccountRecord();
ar1.AccountValues.Add(new AccountValue { ID = 1, value = 10 });
ar1.AccountValues.Add(new AccountValue { ID = 1, value = 70 });
ar1.AccountValues.Add(new AccountValue { ID = 2, value = 90 });
ar1.AccountValues.Add(new AccountValue { ID = 2, value = 60 });
ar1.AccountValues.Add(new AccountValue { ID = 3, value = 20 });
acc.AccountRecords.Add(ar1);
我想从Acc对象
获取ID值的总和答案 0 :(得分:1)
我猜你正在寻找类似的东西:
Account accountObj = new Account();
var result = accountObj.AccountRecords
.SelectMany(r => r.AccountValues)
.GroupBy(r => r.ID)
.Select(grp => new
{
ID = grp.Key,
Sum = grp.Sum(t => t.value)
});