联机分组
本文关键字:联机 | 更新日期: 2023-09-27 18:02:47
我有以下文档列表:
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根据'Name'和'DocCount'的总和对上述列表进行分组并存储在另一个列表中?我想要像这样:
Name = "Customer1", DocCount = 20
Name = "Customer2", DocCount = 10
Name = "Customer3", DocCount = 3
var results = list1.GroupBy(i => i.Name)
.Select(g => new
{
Name = g.Key,
DocCount = g.Sum(i => i.DocCount)
});
var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
{
Name = g.Key,
DocCount = g.Sum(x => x.DocCount)
});
试试这个:
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
}
试试;
var anotherlist = list1.GroupBy(g => g.Name)
.Select(s => new
{
Name = s.Key,
DocCount = s.Sum(i => i.DocCount)
});
简单地说,就是基于Name
分组得到DocCount
及其Name
性质的和。
这里有另一种方法来做相同的
var sumOfDocs = from doc in list1 group doc by doc.Name into g
select new { DocName = g.Key, DocSum = g.Sum(i => i.DocCount) };