How do I write a LINQ query as a single query?

I have the following query for the location of the groups and the average cost of the item, and I would like to write it as one query, but I cannot understand the syntax. What LINQ do I need to do? I've tried writing it in different ways, but the syntax is wrong.

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

      

+3


source to share


1 answer


Well, if you put the first expression in parentheses, it should allow you to join both expressions as they are. Also, I would probably get rid of the second anonymous type for performance reasons (the string is new { m.Location}

redundant, you can use instead .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)
        });

      

+2


source







All Articles