Skip to content

Instantly share code, notes, and snippets.

@skonik
Created January 16, 2020 21:02
Show Gist options
  • Save skonik/9a544f51f7cfee1a2e1e17ced8420af8 to your computer and use it in GitHub Desktop.
Save skonik/9a544f51f7cfee1a2e1e17ced8420af8 to your computer and use it in GitHub Desktop.
Linq GroupJoin
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace tutorials
{
class Customer
{
public string City { get; set; }
public string Title { get; set; }
}
class Provider
{
public string City { get; set; }
public string Title { get; set; }
}
class MainClass
{
public static void Main(string[] args)
{
var customers = new List<Customer>
{
new Customer { Title = "EPAM", City = "Krasnodar" },
new Customer { Title = "SML", City = "Krasnodar" },
new Customer { Title = "MailRu", City = "Moscow" },
new Customer{ Title = "Rambler", City = "Moscow"},
};
var providers = new List<Provider>
{
new Provider{ Title = "Kuban Milk", City = "Krasnodar" },
new Provider{ Title = "Kuban products", City = "Krasnodar" },
new Provider{ Title = "Moscow products", City = "Moscow" },
new Provider{ Title = "Moscow milk", City = "Moscow" },
};
var query = customers.GroupJoin(
providers, // Second Collection for join
customer => customer.City, // Join element from first collection
provider => provider.City, // Join element from second collection
(customer, providerCollection) => // Result element
new {
Customer = customer,
Providers = providerCollection
});
foreach (var item in query)
{
Console.WriteLine($"{item.Customer.Title} from {item.Customer.City}");
foreach(var provider in item.Providers)
{
Console.WriteLine($" {provider.Title} from {provider.City}");
}
}
/*
EPAM from Krasnodar
Kuban Milk from Krasnodar
Kuban products from Krasnodar
SML from Krasnodar
Kuban Milk from Krasnodar
Kuban products from Krasnodar
MailRu from Moscow
Moscow products from Moscow
Moscow milk from Moscow
Rambler from Moscow
Moscow products from Moscow
Moscow milk from Moscow
*/
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment