码迷,mamicode.com
首页 > 数据库 > 详细

LINQ系列:LINQ to SQL Concat/Union

时间:2014-10-25 20:02:23      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   strong   sp   div   

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]

LINQ系列:LINQ to SQL Concat/Union

标签:style   blog   color   io   ar   for   strong   sp   div   

原文地址:http://www.cnblogs.com/libingql/p/4050761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!