Using pivot table in linq(在 linq 中使用数据透视表)
本文介绍了在 linq 中使用数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下动态列表
Crew NameSurname Period Result
ABC John DOE Q1 54,09
ABC John DOE Q2 59,57
ABC John DOE Q3 62,11
我怎样才能在 linq 中得到这个结果.
How can I get this result with in linq.
Crew NameSurname Q1 Q2 Q3
ABC John DOE 47,51 47,51 51,46
我试过这种方法,但我无法得到结果
I've tried this way but I couldn't get the result
List.GroupBy(c => c.PersonnelID)
.Select(g => new
{
PersonnelID = g.Key,
Period1 = g.Where(c => c.Period == 1).Sum(c => c.Result),
Period2 = g.Where(c => c.Period == 2).Sum(c => c.Result),
Period3 = g.Where(c => c.Period == 3).Sum(c => c.Result)
});
推荐答案
你可以这样做:
var results = Data.GroupBy(l => new { l.Crew, l.NameSurname});
.SelectMany( (key, g) =>
new
{
Crew = Key.Crew,
NameSurname = Key.NameSurname,
groups = g
});
var pivoted = new List<PivotedCrew>();
foreach(var item in results)
{
pivoted.Add(
new PivotedCrew
{
Crew = item.Crew,
NameSurname = item.NameSurname,
Q1 = item.groups.Where(x => x.Period == "Q1")
.FirstOrDefault().value,
Q2 = item.groups.Where(x => x.Period == "Q2")
.FirstOrDefault().value,
Q3 = item.groups.Where(x => x.Period == "Q3")
.FirstOrDefault().value
});
}
但是您需要定义一个新类.比如:
But you will need to define a new class. Something like:
public class PivotedCrew
{
public string Crew Id {get; set;}
public string NameSurname {get; set;}
public string Q1 {get; set;}
public string Q2 {get; set;}
public string Q3 {get; set;}
}
这篇关于在 linq 中使用数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在 linq 中使用数据透视表


猜你喜欢
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01