开发者

Convert simple SQL group-by into LINQ to SQL

I'm having trouble.开发者_开发问答 I can't understand existing answers to this on Stack Overflow and am too new to LINQ to SQL to be able to nut it out myself.

See this 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

Returns a nice 2-column table with product names on the left and the total number that product which have been ordered (across all orders) in the right column. How can I duplicate this in LINQ to SQL?

Here is what I've got so far:

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, ... );

What goes at the ... ?


It looks to me like you want:

.Select(g => new { ProductName = g.Key, TotalOrdered = g.Sum(x => x.NumberOf) })

You can do your whole query as either a single query expression or without using query expressions at all though:

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()) 
                                });

Or:

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() };


TotalOrdered = g.Sum(o => o.NumberOf)

make use of above for .... than statement might be

   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) };


Just pasting this here in case it is helpful to know how this could be achieved through GroupJoin method:

var totalProducts = ctx.Products.GroupJoin(ctx.Orders,
    outerKeySelProduct => outerKeySelProduct.Id,
    innerKeySelOrder => innerKeySelOrder.ProductId,
    (outerKeySelProduct, innerKeySelOrder) => new
    {
        ProductName = outerKeySelProduct.Name,
        TotalOrdered = innerKeySelOrder.Select(n => n.NumberOf).Sum()
    });

Happy for it to be edited if it can be improved.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜