简体   繁体   中英

Merge two rows into single row based on a column using LINQ C#

I have a object list like below. I want to join every two rows into single row based on column B. It is sure that only two rows would be there for every single column B value.

Input

在此处输入图像描述

Output

在此处输入图像描述

However, I have done it and solution works. but I am looking for more better solution. I am not much happy with my solution.

My solution:

var groupByItems = items.GroupBy(x => x.ColumnB).Select(x => new MappingClass
        {
            ColumnA= x.FirstOrDefault().ColumnA,
            ColumnB= x.FirstOrDefault().ColumnB,
            ColumnC= x.Where(r=> !string.IsNullOrEmpty(r.ColumnC)).Select(r=>r.ColumnC).FirstOrDefault(),
            ColumnD= x.Where(r => !string.IsNullOrEmpty(r.ColumnD)).Select(r => r.ColumnD).FirstOrDefault(),
        }).ToList();

Now groupByItems object returns me two rows as expected.

You can use Key of the Groups generated by GroupBy() Also, there's no need to use .Where() you can simply put your filter as a lambda expression in .FirstOrDefault() for ColumnC & ColumnD

var groupByItems = items.GroupBy(x => new { ColumnA = x.ColumnA, ColumnB = x.ColumnB })
                        .Select(x => new MappingClass
                        {
                            ColumnA = x.Key.ColumnA,
                            ColumnB = x.Key.ColumnB,
                            ColumnC = x.FirstOrDefault(m => !string.IsNullOrEmpty(m.ColumnC)).ColumnC,
                            ColumnD = x.FirstOrDefault(m => !string.IsNullOrEmpty(m.ColumnD)).ColumnD
                        })
                        .ToList();

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