如何将LINQ查询编写为一个查询?

时间:2017-04-30 18:05:02

标签: linq

我有以下查询分组位置和平均项目成本,我想把它写成一个查询,但我无法弄清楚语法。 LINQ我需要做什么?我尝试用不同的方式编写它,但语法不正确。

        var joinedData =
            from r in shops
            join i in items on r.shopId equals i.shopId 
            select new
            {
                Region = r.Location,
                ItemCost = i.ItemCost
            };

        var AverageCostByLocation = joinedData
            .GroupBy(m => new { m.Location})
            .Select(m => new
            {
                Location= m.Key.Location,
                AverageItemCost = m.Average(x => x.ItemCost)
            });

1 个答案:

答案 0 :(得分:1)

好吧,如果你把第一个表达式放在括号中,它应该允许连接两个表达式。另外,出于性能原因,我可能会删除第二个匿名类型(new { m.Location}行是多余的,您可能想要使用.Key代替):

var AverageCostByLocation =
        (from r in shops
        join i in items on r.shopId equals i.shopId 
        select new
        {
            Region = r.Location,
            ItemCost = i.ItemCost
        })
        .GroupBy(m => m.Location)
        .Select(m => new
        {
            Location= m.Key,
            AverageItemCost = m.Average(x => x.ItemCost)
        });