如何将2个linq语句与group by子句合并为1

时间:2010-03-15 16:24:29

标签: c# linq

我想知道我是否可以将2个linq的声明合并为1个声明。我确信它应该是可能的,但我无法管理各种尝试。

var prevProvisionsBySubBook = (from provision in prevProvisions
               group provision by provision.SubBook
                   into subBookGrouping
                   select
                   new
                   {
                       Key = subBookGrouping.Key,
                       Value = subBookGrouping.Sum(t => t.ProvisionUSD)
                   });


        var currentProvisionsBySubBook
            = (from provision in currentProvisions
               group provision by provision.SubBook
                   into subBookGrouping
                   select new
                   {
                       Key = subBookGrouping.Key,
                       Value = subBookGrouping.Sum(t => t.ProvisionUSD)
                   });

        var adjustmentChangeBySubBook
            = (from current in currentProvisionsBySubBook
               select new
               {
                   Key = current.Key,
                   Value = current.Value
                           - (prevProvisionsBySubBook.Any() ? prevProvisionsBySubBook.Where(t => t.Key == current.Key).Single().Value : 0)
               });

任何帮助都会得到帮助。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

var adjustmentChangeBySubBook =
    from provision in
        (from currentProvision in currentProvisions select new
            {
                currentProvision.SubBook,
                CurrentUSD = currentProvision.ProvisionUSD,
                PreviousUSD = 0
            }).Concat
        (from prevProvision in prevProvisions select new
            {
                prevProvision.SubBook,
                CurrentUSD = 0,
                PreviousUSD = prevProvision.ProvisionUSD
            })
    group provision by provision.SubBook into subBookGrouping select new
    {
        subBookGrouping.Key,
        Value = subBookGrouping.Sum(t => t.CurrentUSD - t.PreviousUSD)
    };