-1

Possible Duplicate:
LINQ Lambda Group By with Sum

LINQ Query or query to table in C# required.

i have a dynamically created DATA Table :

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

Want to Group by city, calc sum of depositamount for specified Deposittype.

Example, for condition depositType= new

i want a row like

           city1 city2 city3
            300   200   100

I want sum of DepositAmounts Grouped by City with specific Deposit type. i.e Result row should have city1 city2 city3 as column names, under which sum of 'Depositamounts' for a specified loan type say 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 に答える