Are you looking forward to create a pivot data using LINQ in C#, here we go.
How to Create Pivot Data using LINQ in C#?
Below is a sample code snippet that demonstrates the creation of the Pivot Data using LINQ and C#?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbundantcodeConsole { class Program { static void Main(string[] args) { //How to Create Pivot Data using LINQ in C# ? List emp = new List(); emp.Add(new Employee { EmpID = 1, SalaryDate = new DateTime(2008, 1, 1), Salary = 1234 }); emp.Add(new Employee { EmpID = 1, SalaryDate = new DateTime(2009, 2, 1), Salary = 456 }); emp.Add(new Employee { EmpID = 2, SalaryDate = new DateTime(2008, 1, 1), Salary = 2234 }); emp.Add(new Employee { EmpID = 2, SalaryDate = new DateTime(2009, 2, 1), Salary = 121345 }); emp.Add(new Employee { EmpID = 3, SalaryDate = new DateTime(2003, 2, 1), Salary = 1245 }); emp.Add(new Employee { EmpID = 3, SalaryDate = new DateTime(2011, 3, 1), Salary = 5623 }); var result = emp .GroupBy(c => c.EmpID) .Select(g => new { EmpID = g.Key, Jan = g.Where(c => c.SalaryDate.Month == 1).Sum(c => c.Salary), Feb = g.Where(c => c.SalaryDate.Month == 2).Sum(c => c.Salary), March = g.Where(c => c.SalaryDate.Month == 3).Sum(c => c.Salary) }); foreach (var data in result) { Console.WriteLine(data.EmpID + " , " + data.Jan + " , " + data.Feb + " , " + data.March); } Console.ReadLine(); } } public class Employee { public int EmpID { get; set; } public DateTime SalaryDate { get; set; } public double Salary { get; set; } } }
Leave a Reply