0

I have a following list of documents:

List<DocumentInfo> list1 = new List<DocumentInfo>()
{
   new DocumentInfo { Name = "Customer1", DocCount = 5 },
   new DocumentInfo { Name = "Customer1", DocCount = 10 },
   new DocumentInfo { Name = "Customer1", DocCount = 5 },
   new DocumentInfo { Name = "Customer2", DocCount = 4 },
   new DocumentInfo { Name = "Customer2", DocCount = 6 },
   new DocumentInfo { Name = "Customer3", DocCount = 3 }
};

How to group the above list based on 'Name' and sum of 'DocCount' using Linq and store in another list? I want something like following:

Name = "Customer1", DocCount = 20
Name = "Customer2", DocCount = 10
Name = "Customer3", DocCount = 3
ekad
  • 14,436
  • 26
  • 44
  • 46
mrd
  • 2,095
  • 6
  • 23
  • 48

6 Answers6

4
var results = list1.GroupBy(i => i.Name)
                   .Select(g => new
                                {
                                    Name = g.Key,
                                    DocCount = g.Sum(i => i.DocCount)
                                });
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1
var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
                                      {
                                          Name = g.Key,
                                          DocCount = g.Sum(x => x.DocCount)
                                      });
cuongle
  • 74,024
  • 28
  • 151
  • 206
1

Try this:

list1.GroupBy(di => di.Name).Select(g => new DocumentInfo {Name = g.Key, DocCount = g.Sum(dc => dc.DocCount)});
aush
  • 2,108
  • 1
  • 14
  • 24
0

Try like this;

var anotherlist = list1.GroupBy(g => g.Name)
                  .Select(s => new
                  {
                      Name = s.Key,
                      DocCount = s.Sum(i => i.DocCount)
                  });

It is simply, getting sum of DocCount and their Name properties by grouping based Name.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0
var result= from item in list1
            group item by item.Name
            into g
            select g;
var groupedInfo = result.SelectMany(group => group);
foreach(var g in groupedInfo)
{
     //Do Summation
}
David
  • 15,894
  • 22
  • 55
  • 66
0

Here is another way to do the same

var sumOfDocs = from doc in list1 group doc by doc.Name into g 
                select new { DocName = g.Key, DocSum = g.Sum(i => i.DocCount) };
Sriwantha Attanayake
  • 7,694
  • 5
  • 42
  • 44