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?
source
share