-2

'I have two lists with different objects. I want to combine all of the data into object3. Id is the common field in all the objects'

'Object1 -> has ID, Name'

'Object2 -> has ID, Street, City'

'Object3-> has ID, Name, Street, City'

'''List<Customer> cust = new List<Customer>();
List<Order> order = new List<Order>();
List<OrderDetails> orderDetails = new List<OrderDetails>();

Customer obj = new Customer();
obj.ID = 5; obj.Name = "Sam"; cust.Add(obj);

Customer obj1 = new Customer();
obj.ID = 6; obj.Name = "Ram"; cust.Add(obj1);

Customer obj2 = new Customer();
obj.ID = 7; obj.Name = "Alex"; cust.Add(obj2);

Order order1 = new Order();
order1.ID = 5; order1.Product = "Book"; order.Add(order1);

Order order2 = new Order();
order2.ID = 6; order2.Product = "Game"; order.Add(order2);

Order order3 = new Order();
order3.ID = 8; order2.Product = "Computer"; order.Add(order3);

var od = from c in cust
         join o in order
         on c.ID equals o.ID
         select new OrderDetails
         {
             ID = c.ID,
             Name = c.Name,
             Product = o.Product
         };

orderDetails = od.ToList();'''

'orderDetails count is 0'

Any help is appreciated.

Buddy26
  • 39
  • 1
  • 6
  • Did you checked this https://stackoverflow.com/questions/24579324/how-merge-two-lists-of-different-objects/24579534 – Developer Sep 17 '21 at 04:39
  • If you have any problems getting this to work using _LINQ_ (hint `join` on the `ID` field), come back and ask a question. We don't just write your code for you – Flydog57 Sep 17 '21 at 04:40
  • This one too https://stackoverflow.com/questions/36759593/merge-2-lists-of-different-types-using-linq – Developer Sep 17 '21 at 04:40
  • The query is executing without error but resultant count is 0. I updated my question with additional details. – Buddy26 Sep 17 '21 at 20:55

1 Answers1

0
  • Initialize a list to hold items of type Object3
  • Loop through the list which has items of type Object1
  • While looping, based on the ID, find the match within the second list
  • If it does not have a match, continue
  • If it has a match, create an object of type Object3 with information from the item being looped (Object1) and the match (Object2). Add it to the list which you created in first step.

You now have a list of Object3 as per your requirement.

Now, it's just a matter of syntax and then adding some sugar if you like it that way.