KeenUser KeenUser - 2 months ago 18
C# Question

C# Convert columns to rows using linq?

I have the following table structure. I want to retrieve value corresponding to key for each group name and insert it store it sequentially in a model class

the table data has been read using a

and stored in a list of class object, in the below example I will have 4 rows returned. I need to convert it into 2 rows, the column values coming in as rows.

Table Data Structure

I have the following code written now, But is there any other way to verify it without explicitly checking for say
Key == "GroupSpecificProperty1"

If there is a 3rd category added later, I shouldn't have to modify this code

Result = results.GroupBy(p => p.GroupName )
.Select(g => new FinalModel()
GroupName = g.Select(p => p.GroupName ).FirstOrDefault(),
GroupSpecificProperty1 = g.Where(q => q.Key == "GroupSpecificProperty1").Select(v => v.Value).Cast<string>().FirstOrDefault(),
GroupSpecificProperty2= g.Where(q => q.Key == "GroupSpecificProperty2").Select(v => v.Value).Cast<string>().FirstOrDefault(),

results.GroupBy(p => p.GroupName)
            .Select(g => new FinalModel
                GroupName = g.Key,
                Properties = g.ToDictionary(item => item.Key, item=> item.Value)

And in the case that for a given GroupName the keys are not unique and you'd want to avoid a "key already exists" exception then you can:

results.GroupBy(p => p.GroupName)
        .Select(g => new FinalModel
            GroupName = g.Key,
            Properties = g.GroupBy(item => item.key)
                          .ToDictionary(innerGroup => innerGroup.Key, 
                                        innerGroup =>  innerGroup.Select(innerItem => innerItem.Value))

Then of course you can also replace the outer/inner dictionary with a LookUp if it fits your needs better.