Home >Backend Development >C++ >How to Join Multiple Tables in LINQ Using Lambda Expressions?

How to Join Multiple Tables in LINQ Using Lambda Expressions?

Susan Sarandon
Susan SarandonOriginal
2025-01-10 10:58:42254browse

How to Join Multiple Tables in LINQ Using Lambda Expressions?

Join multiple tables using LINQ Lambda expressions

When working with multiple tables in LINQ, you may need to join them to collect related data. This can be achieved through lambda expressions in LINQ.

Assume the following scenario:

  • You have classes for Product, Category, and ProductCategory (associated table).
  • You want to join all three tables and populate another object (CategorizedProducts) with specific properties.

The following is an updated version of the code that uses lambda expressions to perform the join:

<code class="language-csharp">var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
    .Select(m => new CategorizedProducts
    {
        ProdId = m.ppc.p.Id, // 或 m.ppc.pc.ProdId
        CatId = m.c.CatId,
        // 其他赋值
    });</code>

In this code:

  • Join operation joins tables based on specified conditions.
  • Anonymous types serve as intermediate representations for concatenated data.
  • Select operation projects the required properties into the CategorizedProducts object.

This solution provides a single class that contains all the properties in the join table, allowing you to populate the CategorizedProducts object as needed.

The above is the detailed content of How to Join Multiple Tables in LINQ Using Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn