How to Create Pivot Data using LINQ in C#?

Published on February 18, 2014 by abundantcode

Filed under LINQ

Last modified February 18, 2014

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 1 (2 votes)

This article have been viewed 9386 times

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 Comment


x

You might be Interested in these Posts

How to decode a base64 string in C#?

Here's a sample code snippet demonstrating how you can easily decode a base64 encoded string in C#. ...

How to disable editing of items in a combo box in c#?

When working in Win forms using C# and especially when you use the combo box , you would have notice...

C# Program to find the ASCII Value of a Character

Problem Write a program in Visual C# to find the ASCII value of the input character. How to find t...