Donny Tellu
Donny Tellu

Reputation: 21

How to join two customer lists into one list

I have two classes:
1. a customer class, which contains the id and name of the customer
2. a customer_details class, which contain the address of the customer and so on

class customer
{
    public int customer_id { get; set; }
    public string name { get; set; }
    //and so on
}
class customer_details
{
    public int customer_id { get; set; }
    public string address { get; set; }
    //and so on
}

My question is, how can I join a List<customer> and a List<customer_details> to a single list, so it shows me the customer_id, name and address in a single list...

Thanks for your answers

Upvotes: 1

Views: 71

Answers (2)

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

Following is the example using Fluent syntax, which is rather compact and preferred:

customers.Join(
               details,
               c=>c.customer_id,
               d=>d.customer_id,
               (c,d)=>new {c.customer_id, c.name, d.address}
              ).ToList()

Upvotes: 2

Issa Jaber
Issa Jaber

Reputation: 409

You must use the Join Method

Here is an example with your classes

 List<customer> customers = new List<customer>();
 List<customer_details> details = new List<customer_details>();

 var query = (from c in customers
                join d in details on c.customer_id equals d.customer_id
                select new
                {
                    c.customer_id,
                    c.name,
                    d.address,
                }).ToList();

Upvotes: 5

Related Questions