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.
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 id
s. And the result is a list of Three
instances created by combining the values of the matching instances of One
and Two
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With