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

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

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.