How do I join data sources in LINQ?
Category: System.Linq, viewed: 2K time(s).
This example show you how to use the join keyword to join more than one data sources when we are creating LINQ query. In the example we have two objects, the Record object and the Publisher object. We are joining these two objects the get the record title and its publisher name.
To connect the two collection that they were related to each other we use the on ... equals ... syntax. This will match the corresponding property between the Record object and the Publisher object.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Kodecsharp.Example.Linq
{
class LinqJoinDemo
{
public static void Main(string[] args)
{
List<Record> records = new List<Record>() {
new Record(1, "Please Please Me", 1),
new Record(2, "With The Beatles", 1),
new Record(3, "A Hard Day's Night", 2)
};
List<Publisher> publishers = new List<Publisher>() {
new Publisher(1, "Sony Entertainment, Inc"),
new Publisher(2, "Beatles Record Company")
};
var query =
from r in records
join p in publishers on r.PublisherId equals p.Id
select new {
r.Title,
p.PublisherName
};
foreach (var result in query)
{
Console.WriteLine(result.Title + " - " + result.PublisherName);
}
Console.ReadLine();
}
}
class Record
{
private long id;
private string title;
private long publisherId;
public Record(long id, string title, long publisherId)
{
this.id = id;
this.title = title;
this.publisherId = publisherId;
}
public long Id
{
get { return this.id; }
set { this.id = value; }
}
public string Title
{
get { return this.title; }
set { this.title = value; }
}
public long PublisherId
{
get { return this.publisherId; }
set { this.publisherId = value; }
}
}
class Publisher
{
private long id;
private string name;
public Publisher(long id, string name)
{
this.id = id;
this.name = name;
}
public long Id
{
get { return this.id; }
set { this.id = value; }
}
public string PublisherName
{
get { return this.name; }
set { this.name = value; }
}
}
}
The program print the following result:
Please Please Me - Sony Entertainment, Inc
With The Beatles - Sony Entertainment, Inc
A Hard Day's Night - Beatles Record Company