【问题标题】:Find items with same property from list and pick the cheaper of the two items从列表中查找具有相同属性的项目并选择两个项目中更便宜的
【发布时间】:2017-12-13 16:46:31
【问题描述】:

我有一个项目列表,每个项目都有一个类别和与之相关的价格。我想知道如何创建一个 linq 查询,它将首先检查具有相同类别的项目,然后检查两者中哪一个更便宜并从列表中删除更昂贵的项目?

【问题讨论】:

  • 问题是……?

标签: linq query-expressions


【解决方案1】:
items = items.GroupBy(x => x.category )
    .Select(x => new Item(x.Key, x.Select(y => y.price ).Min()))
    .ToList();

【讨论】:

    【解决方案2】:

    你可以试试这个。

            class Item
            {
                public string Category { get; set; }
                public int Price { get; set; }
            }
            var prods = new List<Item>
            {
                new Item { Category = "A", Price = 100},
                new Item { Category = "A", Price = 101},
                new Item { Category = "B", Price = 200},
                new Item { Category = "B", Price = 201},
            };
    
            var data = prods
                .GroupBy(prod => prod.Category)
                .Select(p => new Item { Category = p.Key, Price = p.Min(x => x.Price) })
                .ToList();
    

    【讨论】:

      【解决方案3】:

      你可以这样做。

      foreach (var item in items.GroupBy(s => s.Category))
      {
        var cheaper = item.Min(x => x.Price);
        //you can add it to a list of cheaper items
      }
      

      抱歉,我跳过了删除内容。您可以使用 max 遵循相同的逻辑,然后遍历整个结果,仅获取与该价格不匹配的结果。您可以将所有内容放在同一个 foreach 语句中。仅出于教学目的,这就是为什么我将其放入不同的 foreach 中。

      foreach (var item in items.GroupBy(s => s.Category))
      {
        var expensive = item.Max(x => x.Price);
        var listWithoutMax = item.Select(x => x.Price != expensive.Price).ToList();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        • 1970-01-01
        • 2013-11-15
        • 2022-11-28
        • 1970-01-01
        相关资源
        最近更新 更多