Monday, October 13, 2008

LinQ to SQL (union with multiple fields)

Description:

This example demonstrate how to perform union on two tables using multiple fields.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace LinQExamples
{
class Program
{
static void Main(string[] args)
{
UnionExample();
Console.Read();
}

public static void UnionExample()
{
using (NorthwindDataContext db = new NorthwindDataContext())
{
List<Person> persons = db.Customers
.Select(c => new Person { PersonName = c.ContactName,CountryName= c.Country})
.Union(db.Employees
.Select(c => new Person { PersonName = c.FirstName, CountryName = c.Country}))
.ToList<Person>();

foreach (Person person in persons)
{
Console.WriteLine(person.PersonName + "\t" + person.CountryName);
}
}
}
}

class Person
{
private string personName;
private string countryName;

public string PersonName
{
get { return personName; }
set { personName = value; }
}

public string CountryName
{
get { return countryName; }
set { countryName = value;}
}
}
}

No comments: