即使已分组,LINQ查询也会返回重复项

时间:2017-04-30 15:54:38

标签: linq

我有以下查询,我正在尝试获取每个位置的平均ItemCost。 ShopId链接了Shop.cs个对象和Item.cs个对象。每个商店都有一个位置,我想得到每个地点的物品的平均物品成本。

        var query = from s in shops
                    join e in items
                        on s.shopId equals e.shopId into se
                    group se by new
                    {
                        Location= s.location,
                        Average= se.Average(x => x.ItemCost)
                    } into g
                    orderby g.Key.Average descending
                    select new
                    {
                        Location = g.Key.location,
                        AverageCost = g.Key.average,
                    };

以上的输出是:

London   4.65
Scotland  3.44
London   9.28
London 3.25

我无法弄清楚为什么伦敦在输出中作为重复项返回,并且还有不同的Item值,因为我正在对查询中的数据进行分组。 获得以下输出需要什么LINQ?:

London  5.64 (with all London records grouped)
Scotland 3.44

2 个答案:

答案 0 :(得分:1)

var query = from s in shops join e
     in items 
    on s.shopId equals 
    e.shopId into se 
    group se by new { Location= s.location} into 
    g orderby g.Average(x=>x.e.ItemCost)
     descending 
    select new
     { Location = g.Key.Location, AverageCost = g.Average(x=>x.e.ItemCost)};

试试上面的代码。我已经从group by子句中删除了平均列,因为您只需要按位置分组。

答案 1 :(得分:1)

您的查询中的问题是您正在对位置和平均成本的键进行分组,这与仅按位置分组不同。您需要按位置进行分组,然后确定平均费用。

以下是我提出的建议:

var newQuery =
    from s in shops
    join e in items on s.ShopId equals e.ShopId into se
    group se by s.Location into g
    select new { Location = g.Key, AverageCost = g.SelectMany(x => x.Select(y => y.Cost)).Average() } into t
    orderby t.AverageCost
    select new { t.Location, t.AverageCost}

<强>输入:

var shops = new List<Shop>()
    {
        new Shop() {ShopId = 1, Location = "London"},
        new Shop() {ShopId = 2, Location = "Scotland"},
        new Shop() {ShopId = 3, Location = "London"},
        new Shop() {ShopId = 4, Location = "London"},
    };

var items = new List<Item>()
   {
        new Item{Cost = 1, ShopId = 1},
        new Item{Cost = 5, ShopId = 1},
        new Item{Cost = 2, ShopId = 2},
        new Item{Cost = 2, ShopId = 3},
        new Item{Cost = 3, ShopId = 4},
   };

<强>输出:

Location AverageCost
London   2.75
Scotland 2