stillsmallvoice
stillsmallvoice

Reputation: 523

Dynamic Pivot Linq C#

I have the following collection / table

Category    Type       Detail     Cost

Auto        Hybrid     AC         80
Auto        Hybrid     Sunroof    100
Auto        Standard   AC         120
Motorcycle  Standard   Radio      60

Is there a way with linq to get this to pivot to look like this?

Category     Type      AC     Radio    Sunroof     
Auto         Hybrid    80     0        100 
Auto         Standard  120    0        0
Motorcycle   Standard  0      60       0

The details are dynamic so I can't hard code the value in the linq.

Upvotes: 4

Views: 3959

Answers (1)

Charles Lambert
Charles Lambert

Reputation: 5132

use the let keyword to generate a key for use with the group by clause like so:

var query = from item in list
            let key = new { Category = item.Category, Type = item.Type }
            group new { Detail = item.Detail, Cost = item.Cost } by key;

you can loop through the items returned from the query like so:

foreach(var item in query) {
    Console.WriteLine("{0} {1}: ", item.Key.Category, item.Key.Type);
    foreach(var detail in item) {
        Console.WriteLine("\t{0} {1}", detail.Detail, detail.Cost);
    }
}

it displays the following output

Auto Hybrid:
        AC 80
        Sunroof 100
Auto Standard:
        AC 120
Motorcycle Standard:
        Radio 60

Upvotes: 2

Related Questions