我有以下文件清单:
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
答案 0 :(得分:4)
var results = list1.GroupBy(i => i.Name)
.Select(g => new
{
Name = g.Key,
DocCount = g.Sum(i => i.DocCount)
});
答案 1 :(得分:1)
var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
{
Name = g.Key,
DocCount = g.Sum(x => x.DocCount)
});
答案 2 :(得分:1)
试试这个:
list1.GroupBy(di => di.Name).Select(g => new DocumentInfo {Name = g.Key, DocCount = g.Sum(dc => dc.DocCount)});
答案 3 :(得分:0)
试试这个;
var anotherlist = list1.GroupBy(g => g.Name)
.Select(s => new
{
Name = s.Key,
DocCount = s.Sum(i => i.DocCount)
});
简单地说,通过基于DocCount
的分组获得Name
及其Name
属性的总和。
答案 4 :(得分: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
}
答案 5 :(得分: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) };