How to collect list properties into another list in C #?

please advice, which is the best way to populate a class property in a list with list properties of another class in C #.

I have

class Source { public object A {get; set;} public object B {get; set;} public object C {get; set;} } class Destination { public object A {get; set;} public object B {get; set;} // (A,B) is a unique key public List<object> Cs {get; set;} public object D {get; set;} } 

then i have

 List <Destination> destinations; // Cs = null List <Source> sources; //may have zero, one or more than one Cs for (A,B) 

How can I populate Cs from destinations (or another class) using C sources? Can LINQ be used here?

Thanks in advance!

+4
source share
2 answers

Sources for groups A and B (your unique key), and then select C from all the elements in the group:

 var destinations = from s in sources group s by new { sA, sB } into g select new Destination() { A = g.Key.A, B = g.Key.B, Cs = g.Select(x => xC).ToList() }; 

UPDATE if you need to update existing destinations

 foreach(var d in destinations) d.Cs = sources.Where(s => sA == dA && sB && dB).ToList(); 

OR (I believe it will be faster)

 var lookup = sources.ToLookup(s => new { sA, sB }, s => sC); foreach (var d in destinations) d.Cs = lookup[new { dA, dB }].ToList(); 

Demo

+3
source

LINQ to the rescue:

 sources = destinations.SelectMany(d => d.Cs); 

You might want

 sources = destinations.SelectMany(d => d.Cs.Select(c => new Source { A = dA, B = dB, C = c }) ); 
+3
source

All Articles