LINQ - 分组并从两个不同的对象中进行选择

时间:2014-11-10 19:41:28

标签: c# linq

我有两个列表,如

List<First> firstAccount = new List<First>();
List<Second> secondAccount = new List<Second>();

我想选择 列表中的帐户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;

(想选择f.Account,s.Begin,s.End, sum(f.Amount)as Amount) - 不知道如何写这个部分

群组f.Account,s.Begin,s.End

上也会收到错误

1 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

  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)
               };

编辑:这是迄今为止我写过的最丑的LINQ。它应该在理论上有效,假设我对数据结构做出了正确的假设。如果你不明白发生了什么,我强烈建议你弄清楚发生了什么。有大量资源可以解释各种LINQ操作和匿名类型。