Theomax
Theomax

Reputation: 6792

How to write LINQ query as one query?

I have the following query that groups locations and the average item cost and I would like to write it as one query but I cannot figure out the syntax. What LINQ do I need to do this? I have tried writing it different ways but the syntax is not correct.

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

Upvotes: 2

Views: 25

Answers (1)

Fabjan
Fabjan

Reputation: 13676

Well, if you put first expression in parenthesis it should allow to join both expressions as they are. Also I'd probably get rid of second anonymous type for perfomance reasons (the new { m.Location} line is redundant, you might want to use .Key instead) :

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

Upvotes: 1

Related Questions