tags:

views:

48

answers:

1

I have an object "Project" which has a number of fields, one of which is "Name". I have one spreadsheet of projects which contains some of these fields, and another which contains the rest. However, Both spreadsheets have the "Name" field.

I've read them in and populated two List, only populating the available fields from that particular source. E.g. a Project from List 1 looks like; {Name="MyProj", Type="Form", Priority=NULL}, whereas a Project from List 2 {Name="MyProj", Type=NULL, Priority="High"}.

Now, I want to merge these two lists into one in which each Project object has all of its fields populated, with the Name field being used to match the elements.

How can I achieve this? Are there any nice ways of doing this concisely?

Thanks

+3  A: 

I would probably use the ?? operator to find the values. A dictionary could be useful.

// put one into a dict for faster access
var dict2 = list2.ToDictionaty(x => x.Name, x);

// merge the lists using ??
var merged = list1.Select(x => 
{
    var p2 = dict2[x.Name];
    return new Project()
    {
      Name = x.Name,
      Type = x.Type ?? p2.Type,
      Priority = x.Priority ?? p2.Priority 
    }
});

Or

var merged = list1
  // join the lists by the name 
  .Join(list2, x => x.Name, x => x.Name, (p1, p2) => new { P1 = p1, P2 = p2 } )
  .Select(x => 
    new Project()
    {
      Name = P1.Name,
      Type = P1.Type ?? P2.Type,
      Priority = P1.Priority ?? P2.Priority 
    });

There are hundred of variants of this. You could only join and and process the result in a foreach to merge the data of one list into the other. Etc.

It gets more complicated when the projects could be missing in one of the lists, and even more complicated if none of the lists is complete. Then it could be useful to create a complete list of project names at the beginning.

Stefan Steinegger
Great, thanks for the suggestions. I took the first sample to base mine off.
C.McAtackney