考慮以下代碼:LINQ - 列出最低價格只有
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);
}
輸出:
1 | 50
1 | 75
1 | 100
3 | 300
2 | 200
其實我希望它輸出:
1 | 50
2 | 200
3 | 300
查詢應只返回的產品價格最低的某種類型。因此,在任何返回的數據中,應該只有每種商品類型中的一種,並按價格排序。
我以爲Enumerable.Range(1, t.count)
在TSQL中做了一個類似於Row_number over
的工作。個人看不出上面的代碼實際上實現了什麼,除非我寫了它完全錯誤。
有什麼建議嗎?
哪裏300是從哪裏來的?它不應該是150嗎? –