Merging every two objects into single single object making group by a property C# LINQ 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, my 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 =&gt; x.ColumnB).Select(x =&gt; new MappingClass
    {
        ColumnA= x.FirstOrDefault().ColumnA,
        ColumnB= x.FirstOrDefault().ColumnB,
        ColumnC= x.Where(r=&gt; !string.IsNullOrEmpty(r.ColumnC)).Select(r=&gt;r.ColumnC).FirstOrDefault(),
        ColumnD= x.Where(r =&gt; !string.IsNullOrEmpty(r.ColumnD)).Select(r =&gt; r.ColumnD).FirstOrDefault(),
    }).ToList();

Now groupByItems object returns me two rows as expected.
If you want to reduce the iteration to get the value for ColumnC and ColumnD and make the code cleaner, you can try using Aggregate instead.
var output = input
             .GroupBy(d =&gt; new {d.ColumnA, d.ColumnB})
             .Select(
                 g =&gt; g.Aggregate(
                     new MappingClass {ColumnA = g.Key.ColumnA, ColumnB = g.Key.ColumnB},
                     (result, next) =&gt;
                     {
                         result.ColumnC ??= next.ColumnC;
                         result.ColumnD ??= next.ColumnD;
                         return result;
                     }))
              .ToList();