开发者

Merge two lists of objects which hold different data

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 contain开发者_开发知识库s the rest. However, both spreadsheets have the Name field.

I've read them in and populated two List<Project>, 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜