LINQ - Lowest Price List

Consider this code:

var items = (new[] { 
    new {itemTypeId = 1 , cost=100 },
    new {itemTypeId = 2 , cost=200 },
    new {itemTypeId = 1 , cost=50 },
    new {itemTypeId = 3 , cost=150 },
    new {itemTypeId = 1 , cost=75 }
});

var o = items.OrderBy(x => x.cost)
    .ToList()
    .GroupBy(x => x.itemTypeId )
    .Select(g => new { g, count = g.Count() })
    .SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.itemTypeId , j.cost }));

foreach (var i in o)
{
    Console.WriteLine("{0} {1} ", i.itemTypeId, i.cost);
}

Output:

1 | 50  
1 | 75  
1 | 100  
3 | 300  
2 | 200

I really want it to output:

1 | 50   
2 | 200
3 | 300

The request should only return products of a certain type with the lowest price. Therefore, in any returned data, there must be only one of each type of element and is ordered by price.

I thought I Enumerable.Range(1, t.count)completed a similar task Row_number overin TSQL. Personally, I do not see that in fact the above code is really achieved if I did not write that it is wrong.

Any suggestions?

+4
source share
2 answers

You need to group by itemTypeId, and then take the smallest, sorting the group intocost:

var o = items
    .GroupBy(x => x.itemTypeId)
    .Select(g => g.OrderBy(x => x.cost).First())
    .OrderBy(x => x.cost);
+6
source

, IGrouping<T>, IEnumerable<T> . (Select) , Min IGrouping<T>, x, :

items
    .GroupBy(x => x.itemTypeId)
    .Select(x => new { ItemTypeId = x.Key, Cost = x.Min(z => z.cost) })
    .OrderBy(x => x.Cost)
+7

Source: https://habr.com/ru/post/1614622/


All Articles