OpenStack OpenStack - 3 months ago 15
ASP.NET (C#) Question

Combine two list of object in C# when their structure does not match

I have two classe

Class One{
int id;
string name;
int total;
int val2;
int level;
}


Class Two{
int id;
string name;
string parentName;
int parentId;
int level;
}


class One contains information about id, name & some numeric fields.
Class Two on the other hand contains id, names (which contains same data as in class One) but it also contains hierarchical information. Like who is the parent of current node & the level info (which is available in class One)

I need to merge the two classes based on Id field & produce result like this:

class Three{
int id;
string name;
string parentName;
int parentId;
int level;
int total;
int val2;
}


What is the most efficient way to get the desired result in C#. If the list were same, we could have used the Concat method.

Answer

You can use LINQ's Join() method for that:

List<One> l1 = .... // your source list of One
List<Two> l2 = .... // your source list of Two

List<Three> = l1.Join(l2, x1 => x1.id, x2 => x2.id, 
                      (x1, x2) => new Three {
                           id = x1.id,
                           name = x1.name,
                           parentName = x2.parentName,
                           parentId = x2.parentName,
                           level = x1.level,                             
                           total = x1.total
                           val2 = x1.val2}).ToList();

This combines the elements of both source lists based on equal ids. And the result is a list of Three instances created by combining the values of the matching instances of One and Two.

Comments