Find items with same property from list and pick the cheaper of the two items

71 Views Asked by At

I have a list of items each with a category and price associated with them. I wanted to know how to create a linq query that will first check for items with of the same category and then check which one of the two is cheaper and remove the more expensive item from the list?

3

There are 3 best solutions below

0
On BEST ANSWER
items = items.GroupBy(x => x.category )
    .Select(x => new Item(x.Key, x.Select(y => y.price ).Min()))
    .ToList();
0
On

You can do this.

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
}

Sorry I skipped the remove stuff. You can follow the same logic using max and afterwards iterating through the entire result getting only the ones that do not match that price. You can put everything inside of the same foreach statement. For teaching purposes only it's why I put it into a different 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();
}
0
On

You can try this.

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