[英]How to Group and sum values of two Column in C# Linq
I have this Code.我有这个代码。 I am unable to add more columns like Date, Name...我无法添加更多列,例如日期、名称...
var dtt = dt.AsEnumerable()
.GroupBy(p => p.Field<Int64>("ID"))
.Select(p => new
{
ID = p.Key,
Debit = p.Sum(a => a.Field<Decimal>("Debit")),
Credit = p.Sum(a => a.Field<Decimal>("Credit"))
}).ToArray();
You can get name and date one of two ways:您可以通过以下两种方式之一获取姓名和日期:
If the Id
will always be tied to the same user (ie their name), then you can group by Id and Name and return the collection of Date
:如果Id
将始终与同一个用户(即他们的名字)相关联,那么您可以按 Id和Name 分组并返回Date
的集合:
var dtt = database.AsEnumerable()
.GroupBy(p => new { p.Field<Int64>("ID"), p.Field<String>("Name")})
.Select(p => new
{
Id = p.Key.ID,
Name = p.Key.Name,
Date = p.Select(a => a.Date),
Debit = p.Sum(a => a.Field<Decimal>("Debit")),
Credit = p.Sum(a => a.Field<Decimal>("Credit"))
}).ToArray();
Or you can use .First()
as mentioned in the comments (and still return the collection of Date
):或者您可以使用评论中提到的.First()
(并且仍然返回Date
的集合):
var dtt = database.AsEnumerable()
.GroupBy(p => p.Id)
.Select(p => new
{
Id = p.Id,
Name = p.First().Field<String>("Name"),
Date = p.Select(a => a.Field<DateTime>("Date")),
Debit = p.Sum(a => a.Field<Decimal>("Debit")),
Credit = p.Sum(a => a.Field<Decimal>("Credit"))
}).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.