Home > Backend Development > C++ > How to Perform Multiple Table Joins Using LINQ Lambda Expressions?

How to Perform Multiple Table Joins Using LINQ Lambda Expressions?

Patricia Arquette
Release: 2025-01-10 10:13:41
Original
557 people have browsed it

How to Perform Multiple Table Joins Using LINQ Lambda Expressions?

Use LINQ Lambda expressions to perform multi-table joins

LINQ allows joining multiple tables using lambda expressions. Let's say we have three classes:

<code>Product { Id, ProdName, ProdQty }
Category { Id, CatName }
ProductCategory { ProdId, CatId }</code>
Copy after login

Concatenation using Lambda expressions

These tables can be joined using the following code:

<code>var query = product.Join(
    productcategory,
    p => p.Id,
    pc => pc.ProdID,
    (p, pc) => new { product = p, productcategory = pc }
).Join(
    category,
    ppc => ppc.productcategory.CatId,
    c => c.Id,
    (ppc, c) => new { productproductcategory = ppc, category = c }
);</code>
Copy after login

This will generate objects of the following classes:

<code>QueryClass { productproductcategory, category }</code>
Copy after login

Populate new object

To populate a new object with the connection result properties, you can use the following Select method:

<code>var categorizedProducts = query.Select(m => new {
    ProdId = ???, 
    CatId = ???, 
    // 其他赋值
});</code>
Copy after login

Get attribute value

The specific property to be assigned can be obtained from the connected object as follows:

<code>ProdId = m.ppc.p.Id, // 或 m.ppc.pc.ProdId
CatId = m.c.CatId
// 其他赋值</code>
Copy after login

Query syntax alternatives

Alternatively, you can use query syntax, which provides a more concise approach:

<code>var categorizedProducts = from p in product
                       join pc in productcategory on p.Id equals pc.ProdId
                       join c in category on pc.CatId equals c.Id
                       select new {
                           ProdId = p.Id, // 或 pc.ProdId
                           CatId = c.CatId
                           // 其他赋值
                       };</code>
Copy after login

The results of this query are the same as the lambda expression method. If readability is more important, it is recommended to use query syntax.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template