简体   繁体   中英

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 ExecuteQuery 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.

表数据结构
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(),
    }).ToList();
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM