-1

可能重复:
LINQ Lambda Group By with Sum

需要 LINQ 查询或查询到 C# 中的表。

我有一个动态创建的数据表:

            COLUMN:  City    Deposittype  DepositAmount                  
            ROWS :  city1     new          100
                    city1     new          200
                    city2     old          200
                    city2     old          100
                    city2     new          200
                     city3    new          100

想按城市分组,计算指定存款类型的存款金额总和。

例如,对于条件 depositType= new

我想要一行

           city1 city2 city3
            300   200   100

我想要具有特定存款类型的按城市分组的存款金额总和。即结果行应该将city1 city2 city3 作为列名,在该列名下,指定贷款类型的“Depositamounts”总和说Deposittype = new。

4

2 回答 2

1
var result = table.Where(x=>x.Deposit=="new")
                  .GroupBy(x=> x.City)
                  .Select(x=>new { City=x.Key,Sum=x.Sum(y=>y.Amount) } )
                  .ToList();
于 2012-10-21T12:27:55.573 回答
0
    public class Table
    {
        public string City { get; set; }

        public string Deposit { get; set; }

        public decimal Amount { get; set; }
    }

             var list = new List<Table>
                           {
                               new Table { City = "city1", Deposit = "new", Amount = 100 },
                               new Table { City = "city1", Deposit = "new", Amount = 200 },
                               new Table { City = "city2", Deposit = "old", Amount = 200 },
                               new Table { City = "city2", Deposit = "old", Amount = 100 },
                               new Table { City = "city2", Deposit = "new", Amount = 200 },
                               new Table { City = "city3", Deposit = "new", Amount = 100 }
                           };
            //You can get all items by grouping with city and deposit in here.
            var result = (from c in list
                          group c by new {c.City,c.Deposit} into d
                          select new
                          {
                              City = d.Key.City,
                              Deposit = d.Key.Deposit,
                              SumAmount = d.Sum(x => x.Amount)
                          });

            //If you want only new,
            var resultNew = result.Where(x => x.Deposit == "new");
            //If you want only old,
            var resultOld = result.Where(x => x.Deposit == "old");
于 2012-10-21T12:03:31.773 回答