Pivot C# Array or DataTable: Convert a Column To a Row with LINQ(c#列转行)
My previous post explains how to convert a column to row in JavaScript array. In this post, we will do the same thing but with C# Array and DataTable using the power of LINQ or Lambda expression. For simplicity, I am using the same data.
1|0C# Array To Pivot DataTable
- Here is the C# array object:
- On Googling, I found the following generic method in StackOverflow thread:
- You can create a static class for extension methods and put it there.
To convert Year values to columns and get Pivot DataTable:
2|0C# Array to Pivot Dynamic Array
- You might want to get the List
or dynamic[] instead of getting DataTable after converting columns to rows. It is handy in ASP.NET Web API to return JSON response. - To do it, I updated the extension method to get the dynamic object. use following extension method:
- ExpandoObject is used to create dynamic object.
Now, to convert row to column and get dynamic array:
- You can easily convert in JSON format
3|0C# DataTable to Pivot DataTable
- Let us have a DataTable with same data:
- You can use the same extension method to get Pivot DataTable like below.
4|0DataTable to List
- If you need to convert DataTable to List of dynamic object then use following extension method:
5|0Conclusion
In this post, we played with C# Array, DataTable and implemented to convert row to column and get Pivot Array, DataTable and List of dynamic object.
Hope, It helps.
__EOF__

本文作者:vvull
本文链接:https://www.cnblogs.com/vvull/p/14744925.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/vvull/p/14744925.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
分类:
.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?