0

我有以下文件清单:

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 }
};

如何使用 Linq 根据“名称”和“DocCount”的总和对上述列表进行分组并存储在另一个列表中?我想要以下内容:

Name = "Customer1", DocCount = 20
Name = "Customer2", DocCount = 10
Name = "Customer3", DocCount = 3
4

6 回答 6

4
var results = list1.GroupBy(i => i.Name)
                   .Select(g => new
                                {
                                    Name = g.Key,
                                    DocCount = g.Sum(i => i.DocCount)
                                });
于 2013-03-08T07:55:51.413 回答
1
var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
                                      {
                                          Name = g.Key,
                                          DocCount = g.Sum(x => x.DocCount)
                                      });
于 2013-03-08T07:56:30.883 回答
1

试试这个:

list1.GroupBy(di => di.Name).Select(g => new DocumentInfo {Name = g.Key, DocCount = g.Sum(dc => dc.DocCount)});
于 2013-03-08T07:56:36.800 回答
0

试试这样;

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

很简单,通过分组来获取它们的总和DocCount及其Name属性Name

于 2013-03-08T07:57:08.723 回答
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
}
于 2013-03-08T08:00:49.307 回答
0

这是另一种方法

var sumOfDocs = from doc in list1 group doc by doc.Name into g 
                select new { DocName = g.Key, DocSum = g.Sum(i => i.DocCount) };
于 2013-08-02T01:48:40.110 回答