简体   繁体   中英

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 :

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 ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM