Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging two lists with diff structures C#

Tags:

c#

linq

I have a list of objects with structure

string source, string target, int count

Sample data:

sourcea      targeta      10
sourcea      targetb      15
sourcea      targetc      20

My other list of objects is with structure

string source, int addnvalueacount, int addnvaluebcount, int addnvalueccount

Sample data:

sourcea    10    25   35

I wish to change the second list to the first list structure and then do a union all(concat) with first list.

So result ought to look as below:

sourcea      targeta      10
sourcea      targetb      15
sourcea      targetc      20
sourcea      addnlvaluea  10
sourcea      addnlvalueb  25
sourcea      addnlvaluec  35

All help is sincerely appreciated..

Thanks

like image 380
Arnab Avatar asked Dec 20 '16 07:12

Arnab


1 Answers

I suggest Concat with SelectMany; providing you have

List<A> listA = new List<A> {
  new A ("sorcea", "targeta" , 10),
  new A ("sorcea", "targetb" , 15),
  new A ("sorcea", "targetc" , 20),
};

List<B> listB = new List<B> {
  new B ("sourcea", 10, 15, 35),
};

in order to Concat all you have to do is to add SelectMany:

var result = listA
  .Concat(listB
    .SelectMany(item => new [] { // turn single B item into three A
       new A(item.source, "addnvaluea", item.addnvalueacount),
       new A(item.source, "addnvalueb", item.addnvaluebcount),
       new A(item.source, "addnvaluec", item.addnvalueccount),   
      }));
like image 136
Dmitry Bychenko Avatar answered Oct 28 '22 18:10

Dmitry Bychenko