How to build pivot table through linq using c#

前端 未结 2 1281
故里飘歌
故里飘歌 2020-12-04 02:26

I have got this datatable in my c# code:

Date     | Employee | Job1 | Job2 |  Job3 |
---------|----------|------|---         


        
相关标签:
2条回答
  • 2020-12-04 03:14

    You won't be able to do this with LINQ due to the dynamic nature of the columns. LINQ to SQL needs a static way to map result set fields to property values. Instead, you can look into the PIVOT SQL statement and fill the results into a DataTable

    http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

    0 讨论(0)
  • 2020-12-04 03:20
    var query = from foo in db.Foos
                group foo by foo.Date into g
                select new {
                    Date = g.Key,
                    A = g.Where(x => x.Employee == "A").Sum(x => x.Job1),
                    B = g.Where(x => x.Employee == "B").Sum(x => x.Job1),
                    C = g.Where(x => x.Employee == "C").Sum(x => x.Job1),
                    D = g.Where(x => x.Employee == "D").Sum(x => x.Job1),
                    Total = g.Sum(x => x.Job1)
                };
    

    You can also apply OrderBy(x => x.Date) to query.

    0 讨论(0)
提交回复
热议问题