[英]LINQ - Group by and select from two different objects
I have two lists defined like, 我定义了两个列表,
List<First> firstAccount = new List<First>();
List<Second> secondAccount = new List<Second>();
I want to select Account from list firstAccount and Amount always from firstAccount. 我想从列表firstAccount中选择帐户,并且总是从firstAccount中选择金额。
var listofFirstAccounts =
**(want to select f.Account, s.Begin, s.End,
sum(f.Amount) as Amount)** -- Don't know how to write this part
from f in firstAccount
join s in secondAccount
on f.Account equals s.Account
where (
(f.Begin >= s.Begin && f.Begin <= s.End)
&&
(f.End >= s.Begin && f.End <= s.End)
)
group f.Account, s.Begin, s.End //Error Here
select f;
(want to select f.Account, s.Begin, s.End, sum(f.Amount) as Amount) -- Don't know how to write this part (想要选择f.Account,s.Begin,s.End,sum(f.Amount)作为Amount) -不知道如何编写此部分
Also getting error at group f.Account, s.Begin, s.End 在组f.Account,s.Begin,s.End上也出现错误
Something like this should work: 这样的事情应该起作用:
var result = from account in (from first in firstAccount
join second in secondAccount
on first.Account equals second.Account
where
((first.Begin >= second.Begin && first.Begin <= second.Begin) &&
(first.End >= second.Begin && first.End <= second.End)
select new
{
first.Account,
second.Begin,
second.End,
first.Amount
})
group account by new {account.Account, account.Begin, account.End}
into groupedAccounts
select new
{
groupedAccounts.Key.Account,
groupedAccounts.Key.Begin,
groupedAccounts.Key.End,
Sum = groupedAccounts.Sum(a => a.Amount)
};
Edit: This is by far the ugliest LINQ I have ever written. 编辑:这是迄今为止我写过的最丑的LINQ。 It should in theory work, assuming that I made the correct assumptions of your data structures.
假设我对您的数据结构做出了正确的假设,那么它在理论上应该起作用。 If you don't understand what's going on, I highly recommend that you figure out what's going on.
如果您不了解正在发生的事情,我强烈建议您找出正在发生的事情。 There are plenty of resources explaining various LINQ operations and anonymous types.
有大量资源说明各种LINQ操作和匿名类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.