Domanda

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
È stato utile?

Soluzione

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

Altri suggerimenti

var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
                                      {
                                          Name = g.Key,
                                          DocCount = g.Sum(x => x.DocCount)
                                      });

Try this:

list1.GroupBy(di => di.Name).Select(g => new DocumentInfo {Name = g.Key, DocCount = g.Sum(dc => dc.DocCount)});
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
}

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.

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) };
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top