0

I have two tables. I would like to perform a union query uning LINQ to select from two tables but only return one column.

Table 1:

ID, Name1, Email

Table 2:

ID, Name2, Email

Select Name1 and Name2 from the tables to return one column.

So, I'd like to select

Name
--------
Helen 
Mike 
Joe 

Not :

Name1
-------
Helen
Mike 

Name2
-------
Joe
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shekinah Budhai
  • 77
  • 1
  • 2
  • 11

1 Answers1

0

If you need to select only the Names you could,

var result = table1.Select(x=>x.Name1).Union(table2.Select(x=>x.Name2));

For example, emulating your scenario using collection.

var table1 = new List<Table1>
{
    new Table1{ID=1,Name1="Helen ",Email=""},
    new Table1{ID=2,Name1="Mike",Email=""},
};

var table2 = new List<Table2>
{
    new Table2{ID=1,Name2="Joe",Email=""},
};

Where

public class Table1
{
public int ID {get;set;}
public string Name1{get;set;}
public string Email{get;set;}
}

public class Table2
{
public int ID {get;set;}
public string Name2{get;set;}
public string Email{get;set;}
}

The Query would return

Helen  
Mike 
Joe 

Please be aware that Union would be eliminating the duplicates. If you would like to include duplicates, Concat would be the way to go. If you are interested to read more on the difference, this thread would be a good reference

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51