linq query join and in csharp

To join two or more collections using LINQ query syntax in C#, you can use the join keyword followed by the on keyword to specify the join condition. Here's an example that joins two collections based on a common property:

main.cs
var customers = new List<Customer> 
{
    new Customer { Id = 1, Name = "John Smith" },
    new Customer { Id = 2, Name = "Jane Doe" },
    new Customer { Id = 3, Name = "Bob Johnson" }
};

var orders = new List<Order>
{
    new Order { Id = 1, CustomerId = 1, Total = 100 },
    new Order { Id = 2, CustomerId = 2, Total = 200 },
    new Order { Id = 3, CustomerId = 1, Total = 150 },
    new Order { Id = 4, CustomerId = 3, Total = 75 }
};

var results = from c in customers
              join o in orders on c.Id equals o.CustomerId
              select new 
              {
                  CustomerName = c.Name,
                  OrderTotal = o.Total
              };
675 chars
23 lines

In this example, the join keyword is used to join the customers and orders collections based on the Id and CustomerId properties, respectively. The resulting collection consists of anonymous objects with the CustomerName and OrderTotal properties. By using select new you can select what you want to show up in the results. This will only show the Customer name and the Order total, but you can adjust it to your liking.

Note that you can join more than two collections by chaining additional join statements together.

related categories

gistlibby LogSnag