1

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

enter image description here

Output

enter image description here

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.

5
  • 1
    You want to group by column b then? Commented Apr 25, 2021 at 10:18
  • @auburg Yes. want to groupby columnB. Commented Apr 25, 2021 at 10:24
  • So what code have you got so far? What bit are you stuck on? Commented Apr 25, 2021 at 10:38
  • @auburg Added my solution below to the question. However my solution works, but I am not happy with it and looking for more better solution. I think It could. Commented Apr 25, 2021 at 10:42
  • SO isn’t really the place for suggesting improvements to working code. Perhaps post at codereview.stackexchange.com. I don’t see much wrong with what you’re doing Commented Apr 25, 2021 at 10:46

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.