Blog

Join in lambda C#

Lambda

Join in lambda C#

  1. Create a console application and create a customer class and a country class
				
					public class Customer
{
    public int CustomerCode { get; set; }
    public string CustomerName { get; set; }
    public int TotalOrder { get; set; }
}
				
			
				
					public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }
				
			

2. Create a list of customers and countries.

				
					 var customerList = new List<Customer>()
    {
        new Customer{CustomerCode=101,CustomerName = "Steve", TotalOrder = 2, CountryCode="US"},
        new Customer{CustomerCode=102,CustomerName = "Mark", TotalOrder = 4, CountryCode="IN"},
        new Customer{CustomerCode=103,CustomerName = "Bill", TotalOrder = 7, CountryCode="US"},
        new Customer{CustomerCode=104,CustomerName = "Dell",TotalOrder = 6, CountryCode="US"}
    };
				
			

 

 

				
					var countryList = new List<Country>()
    {
        new Country{CountryCode="US", CountryName="America"},
        new Country{CountryCode="IN", CountryName="India"},
        new Country{CountryCode="ME", CountryName="Mexico"},
        new Country{CountryCode="UK", CountryName="United Kingdom"}
    };
				
			

3. Join in lambda between two classes

				
					var result = customerList.Join(countryList, a => a.CountryCode, b => b.CountryCode, (a, b) => new
    {
        a.CustomerCode,
        a.CustomerName,
        b.CountryName
    }).ToList();
    
    result.ForEach(a => Console.WriteLine($"{a.CustomerCode} | {a.CountryName} | {a.CountryName}"));
    Console.ReadLine();
				
			
dotnet tutorial, dotnetcoaching

Please comment and share if you like this post and tell us about how we can enhance our posts. Thanks.

Subhajit