Skip to content

Instantly share code, notes, and snippets.

@juanonsoftware
Created June 29, 2015 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanonsoftware/b55bcf15923f3f9cd2f4 to your computer and use it in GitHub Desktop.
Save juanonsoftware/b55bcf15923f3f9cd2f4 to your computer and use it in GitHub Desktop.
C# LINQ with join on multiple properties
namespace ConsoleApplication1
{
public class Context
{
public IList<Product> Products { get; set; }
public IList<Company> Companies { get; set; }
}
public class Product
{
public string Name { get; set; }
public string MadeBy { get; set; }
public int Id { get; set; }
public int CompanyId { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string Country { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var ct = new Context()
{
Companies = new List<Company>()
{
new Company()
{
CompanyId = 1,
Country = "VN",
Name = "C1"
},
new Company()
{
CompanyId = 2,
Country = "US",
Name = "C1"
}
},
Products = new List<Product>()
{
new Product()
{
Id = 1,
Name = "P1",
MadeBy = "VN",
CompanyId = 1
}
}
};
var query = from c in ct.Companies
join p in ct.Products on c.CompanyId equals p.CompanyId
select new { CompanyName = c.Name, ProductName = p.Name };
var query2 = from c in ct.Companies
join p in ct.Products on new { c.CompanyId, c.Country } equals new { p.CompanyId, Country = p.MadeBy }
select new { CompanyName = c.Name, ProductName = p.Name };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment