ratherplaytennis
ratherplaytennis

Reputation: 11

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

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?

Upvotes: 0

Views: 60

Answers (3)

Matias
Matias

Reputation: 738

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

Upvotes: 1

Andreas W
Andreas W

Reputation: 275

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

Upvotes: 2

Ayaz
Ayaz

Reputation: 2121

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

Upvotes: 1

Related Questions