将简单的SQL分组转换为LINQ to SQL

Lis*_*isa 16 c# linq group-by linq-to-sql

我遇到了麻烦.我无法理解Stack Overflow上现有的答案,对LINQ to SQL来说太新了,无法自己解决问题.

看到这个SQL:

select p.Name as ProductName, SUM(o.NumberOf) as TotalOrdered from [Order] o
  join [Product] p on o.ProductId = p.Id
  group by p.Name
Run Code Online (Sandbox Code Playgroud)

返回一个漂亮的2列表,其左侧是产品名称,右侧列是已订购产品的总数(所有订单).如何在LINQ to SQL中复制它?

这是我到目前为止所得到的:

var ctx = new DataClasses1DataContext();
var totalProducts = (from o in ctx.Orders
                     join p in ctx.Products on o.ProductId equals p.Id
                     select new { p.Name, o.NumberOf })
    .GroupBy(t => t.Name)
    .Select(g => g.Key, ... );
Run Code Online (Sandbox Code Playgroud)

怎么回事......?

Jon*_*eet 36

它看起来像你想要的:

.Select(g => new { ProductName = g.Key, TotalOrdered = g.Sum(x => x.NumberOf) })
Run Code Online (Sandbox Code Playgroud)

您可以将整个查询作为单个查询表达式执行,也可以根本不使用查询表达式:

var totalProducts = ctx.Orders
                       .Join(ctx.Products, o => o.ProductId, p => p.Id,
                             (o, p) => new { p.Name, o.NumberOf })
                       .GroupBy(t => t.Name,
                                pair => pair.Name, // Key selector
                                pair => pair.NumberOf, // Element selector
                                (key, numbers) => new { 
                                    ProductName = key,
                                    TotalOrdered = numbers.Sum()) 
                                });
Run Code Online (Sandbox Code Playgroud)

要么:

var totalProdcuts = from o in ctx.Orders
                    join p in ctx.Products on o.ProductId equals p.Id
                    group o.NumberOf by p.Name into g
                    select new { ProductName = g.Key, TotalOrdered = g.Sum() };
Run Code Online (Sandbox Code Playgroud)


Pra*_*ana 6

TotalOrdered = g.Sum(o => o.NumberOf)
Run Code Online (Sandbox Code Playgroud)

使用上面的 for .... than 语句可能是

   select new { ProductName=  g.Key, TotalOrdered  = g.Sum(o => o.NumberOf) };

var query = from o in ctx.Orders
            join p in ctx.Products on 
            o.ProductId equals p.Id
            group o by new { p.Name, o.NumberOf } into g
            select new { ProductName=  g.Key, TotalOrdered  = g.Sum(o => o.NumberOf) };
Run Code Online (Sandbox Code Playgroud)