Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two lists in C#

Tags:

c#

merge

list

I want to merge two lists with different attributes into one list, but while merging it, I want to check if there is, in this particular example, exact date that is in the both lists, and if there is, I want to take both attributes from that elements, and merge them into one element in another list

List 1:

List<object> r1 = (from x in sp1 select new 
                   { 
                     x.Imported, 
                     x.Period 
                   }).ToList<object>();

L1 result:

enter image description here

List 2:

List<object> r2 = (from x in sp2 select new 
                   { 
                     x.Dissolution, 
                     x.Period 
                   }).ToList<object>();

L2 result:

enter image description here


Wanted result:

enter image description here

For now, this is how i merge r1 and r2:

 List<object> r3 = new List<object>(r1.Concat(r2));
like image 721
ToTa Avatar asked Nov 01 '22 20:11

ToTa


1 Answers

You could transform them into same type and use stuff like this

r1
.Select(x => new { Imported = x.Imported, Dissolution = null, Period = x.Period)
.Concat(
    r2.Select(x => new { Imported = null, Dissolution = x.Dissolution, Period = x.Period))
.GroupBy(x => x.Period)
.Select(x => new { Imported = x.Max(e => e.Imported),
                   Dissolution = x.Max(e => e.Dissolution),
                   Period = x.Key);
like image 55
nkj Avatar answered Nov 09 '22 14:11

nkj