-2

I have two lists: List a, List b

var a1= new A
{
  Name = "XYZ",
  Id = "123"
};
var a2= new A
{
  Name = "UVW",
  Id = "567"
};
var a = new List<A>()
{
    a1,
    a2
};

public class A
{
    public string Name{ get; set; }
    public string Id{ get; set; }
}


var b1= new B
{
  Location = "US",
  Id = "123"
};
var b2= new B
{
  Location = "IN",
  Id = "567"
};
var b = new List<B>()
{
    b1,
    b2
};

public class B
{
    public string Location{ get; set; }
    public string Id{ get; set; }
}

Notice that Id is common in both A and B classes. The final goal is to have a list that contains values of members from both A and B classes:

var output = new List<AB>()
{
  ab1,
  ab2
}

public class AB
{
    public string Id{ get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
}

Or update List a to include values from List b?

How would I do that in C#?

Mohammed Sajid
  • 4,778
  • 2
  • 15
  • 20
user989988
  • 3,006
  • 7
  • 44
  • 91
  • If you describe your actual goal it might help. What are you trying to achieve by doing this? I feel like you're over-complicating a rather simple problem. – Sach Jul 07 '20 at 22:42
  • Maybe show some sample input and output of what you want. – Sach Jul 07 '20 at 22:53
  • Does this answer your question? [How to join two Lists based on common property](https://stackoverflow.com/questions/25645679/how-to-join-two-lists-based-on-common-property) – Pavel Anikhouski Jul 08 '20 at 08:20

1 Answers1

1

You could use Join to get common data based on Id and populate AB, like the following code :

var output = aList.Join(bList,
    a => a.Id,
    b => b.Id,
    (a, b) => new AB
    {
        Id = a.Id,
        Location = b.Location,
        Name = a.Name
    }).ToList();

Demo

foreach(var item in output)
{
   Console.WriteLine($"Id:{item.Id}, Name : {item.Name}, Location:{item.Location}");
}

Result:

Id:123, Name : XYZ, Location:US
Id:567, Name : UVW, Location:IN

Demo in dotnetfiddle : https://dotnetfiddle.net/3ZbK6c

I hope you find this helpful.

Mohammed Sajid
  • 4,778
  • 2
  • 15
  • 20