1

I have a troubles with linq.

I need to get from this:

+---------+---------+-------+
| Package | WorkDay | Hours |
+---------+---------+-------+
| Pack1   | 03/01   |     8 |
| Pack1   | 03/01   |     7 |
| Pack1   | 03/02   |     6 |
| Pack2   | 03/02   |     4 |
+---------+---------+-------+

to this:

+-------+-------+-------+
|       | 03/01 | 03/02 |
+-------+-------+-------+
| Pack1 |    15 |     6 |
| Pack2 |     0 |     4 |
+-------+-------+-------+

where cell value is the SUM of Hours for that Package for that WorkDay.

This code DOES work, but it produces wrong table layout:

        var query = Time
            .GroupBy(t => new { t.PackageId, t.WorkDay })
            .Select(t => new
            {
                Package = t.FirstOrDefault().Package,
                WorkDay = t.FirstOrDefault().WorkDay,
                Hours = t.Sum(x => x.Hours)
            });

Maybe there is a way to transpose query results? Im not sure how to achieve my goal in elegant way. Could somebody help me please?

Szer
  • 3,426
  • 3
  • 16
  • 36
  • Can you show us what layout the statement above produces? – GVashist Dec 10 '14 at 18:00
  • What is the end use? Grid components and reports are _much_ better at pivoting data then Linq and SQL are. – D Stanley Dec 10 '14 at 18:02
  • @GVashist it produces same layout with needed info, but not in the way I need it: +---------+---------+-------+ | Package | WorkDay | Hours | +---------+---------+-------+ | Pack1 | 03/01 | 15 | | Pack1 | 03/02 | 6 | | Pack2 | 03/02 | 4 | +---------+---------+-------+ Tables doesnt work in comments? – Szer Dec 10 '14 at 18:03
  • @DStanley I need it for something like this: http://i.imgur.com/QAKTdap.png – Szer Dec 10 '14 at 18:08
  • If you're wondering what the duplicate question is, look for "Pivot tables using LINQ" – GVashist Dec 10 '14 at 18:09
  • @Servy I didnt now that it called pivoting! Thank you very much for answer. (problem solved I hope) – Szer Dec 10 '14 at 18:12

0 Answers0