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
我希望按城市分组的DepositAmounts总额与特定存款类型。即结果行应将city1 city2 city3作为列名,其中指定贷款类型的“Depositamounts”总和表示Deposittype = new。
答案 0 :(得分: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();
答案 1 :(得分: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");