How to collect properties of a list to another list in C#?

c#, linq, list

Solution

Group sources by A and B (your unique key), and then select C from all items in group:

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

UPDATE if you need to update existing destinations

foreach(var d in destinations)
   d.Cs = sources.Where(s => s.A == d.A && s.B && d.B).ToList();

OR (I believe this will be faster)

var lookup = sources.ToLookup(s => new { s.A, s.B }, s => s.C);
foreach (var d in destinations)            
     d.Cs = lookup[new { d.A, d.B }].ToList();

DEMO

Problem

please advice which is the best way to fill a class property in the list with properties of list 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 fill Cs of Destinations (or another class) with C of Sources? Is it possible to use LINQ here? Thanks in advance!

Original source