LINQ系列:LINQ to SQL Concat/Union

1. Concat

  单列Concat

var expr = (from p in context.Products
            select p.ProductName)
            .Concat(
            from c in context.Categories
            select c.CategoryName
            );
foreach (var item in expr)
{
    Console.WriteLine(item);
}
var expr = context.Products
    .Select(p => p.ProductName)
    .Concat(
    context.Categories
    .Select(c => c.CategoryName)
    );
SELECT 
    [UnionAll1].[ProductName] AS [C1]
    FROM  (SELECT 
        [Extent1].[ProductName] AS [ProductName]
        FROM [dbo].[Product] AS [Extent1]
    UNION ALL
        SELECT 
        [Extent2].[CategoryName] AS [CategoryName]
        FROM [dbo].[Category] AS [Extent2]) AS [UnionAll1]

  多列Concat

var expr = context.Products
    .Select(p => new 
    {
        p.ProductID, 
        p.ProductName 
    })
    .Concat(
    context.Categories
    .Select(c => new 
    { 
        ProductID = c.CategoryID, 
        ProductName = c.CategoryName 
    })
    );
SELECT 
    [UnionAll1].[ProductID] AS [C1], 
    [UnionAll1].[ProductID1] AS [C2], 
    [UnionAll1].[ProductName] AS [C3]
    FROM  (SELECT 
        [Extent1].[ProductID] AS [ProductID], 
        [Extent1].[ProductID] AS [ProductID1], 
        [Extent1].[ProductName] AS [ProductName]
        FROM [dbo].[Product] AS [Extent1]
    UNION ALL
        SELECT 
        [Extent2].[CategoryID] AS [CategoryID], 
        [Extent2].[CategoryID] AS [CategoryID1], 
        [Extent2].[CategoryName] AS [CategoryName]
        FROM [dbo].[Category] AS [Extent2]) AS [UnionAll1]

2. Union

var expr = context.Products
    .Select(p => p.ProductName)
    .Union(
    context.Categories
    .Select(c => c.CategoryName)
    );
SELECT 
    [Distinct1].[C1] AS [C1]
    FROM ( SELECT DISTINCT 
        [UnionAll1].[ProductName] AS [C1]
        FROM  (SELECT 
            [Extent1].[ProductName] AS [ProductName]
            FROM [dbo].[Product] AS [Extent1]
        UNION ALL
            SELECT 
            [Extent2].[CategoryName] AS [CategoryName]
            FROM [dbo].[Category] AS [Extent2]) AS [UnionAll1]
    )  AS [Distinct1]

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。