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 6914 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 download a file from a URL using C#?

You can use the WebClient class in C# to download a file. How to download a file from a URL using C...

How to Create an Empty array without defining the size in C# ?

When we create an array in C# , we tend to define the size of the array as shown below. String[] st...

C++ Program to display "Hello, World!"

Problem Write a program in C++ to display "Hello, World!" on the screen. C++ Program to...