4

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.

OpenStack
  • 5,048
  • 9
  • 34
  • 69
  • Use List.Zip extension method: http://stackoverflow.com/questions/10297124/how-to-combine-more-than-two-generic-lists-in-c-sharp-zip – Dimitri Aug 22 '16 at 15:47

2 Answers2

9

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.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

I personally find it easier on the eye to use LINQ Query syntax when doing joins. I changed Renè's answer to do just that:

List<One> list1 = ....; // your source list of One
List<Two> list2 = ....; // your source list of Two
List<Three> list3 = (from one in list1
              join two in list2
                  on one.id equals two.id
              select new Three
              {
                  id = one.id,
                  name = one.name,
                  parentName = two.parentName,
                  parentId = two.parentName,
                  level = one.level,
                  total = one.total
                  val2 = one.val2
              }).ToList();
Akanni
  • 924
  • 9
  • 10
David Smit
  • 829
  • 1
  • 13
  • 31