2012-10-21 50 views
-1

可能重复:
LINQ Lambda Group By with SumLINQ查询或查询表中C#与分组和共计

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 depositamount的计算值总和要分组。

例如,对于条件depositType =新

我希望有一个行像

  city1 city2 city3 
      300 200 100 

我想通过市用特定类型的存款条件DepositAmounts的总和。即Result行应该有city1 city2 city3作为列名,在这种情况下,指定的贷款类型的'Depositamounts'的总和应该是Deposittype = new。

回答

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"); 
+0

非常感谢。会试试这个。 –

+0

如果其中一个答案对您有帮助,请考虑将其标记为答案。顺便说一句,这也适用于你的其他问题。 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – sinanakyazici

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(); 
+0

where子句不能用于表 –

+0

@ThejoArjun它取决于“table”的类型。我认为它是'List ' –