Benk
Benk

Reputation: 1312

LINQ query to retrieve from one table and then another

I have 2 tables containing the same fields, e.g. id,name,invoiceNo..etc

I want to use c# ling to get all the data from both tables

I have the below example for 1 table, how do I add the second table?

 return query = from tb1 in dataContext.tbl1
                    select new customer
                    {
                       name= tbl1.name
                    };

Upvotes: 1

Views: 1138

Answers (2)

Servy
Servy

Reputation: 203804

You can just use Concat once you have two sequences of the same type.

return dataContext.tbl1.Select(tb1 => new customer()
{
    name = tb1.name,
})
.Concat(dataContext.tbl2
    .Select(tb2 => new customer()
    {
         name = tb2.name,
    }));

You could use query syntax for the select calls, but I find method syntax preferable in this particular case.

Upvotes: 1

mipe34
mipe34

Reputation: 5666

You can use Union or Concat:

query1 = from tb1 in dataContext.tbl1
                select new customer
                {
                   name= tbl1.name
                };

query2 = from tb2 in dataContext.tbl2
                    select new customer
                    {
                       name= tbl1.name
                    };

var resQuery = query1.Union(query2);

It would be similar with Concat. Main difference between Union and Concat is that Union removes duplicities from the result.

Upvotes: 1

Related Questions