LINQ - 仅列出最低价格

Com*_*umb 4 c# 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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 | 50  
1 | 75  
1 | 100  
3 | 300  
2 | 200
Run Code Online (Sandbox Code Playgroud)

我实际上想要它输出:

1 | 50   
2 | 200
3 | 300
Run Code Online (Sandbox Code Playgroud)

查询应仅返回具有最低价格的特定类型的产品.因此,在任何返回的数据中,每个项目类型应该只有一个,并按价格排序.

我认为在TSQL中Enumerable.Range(1, t.count)做了类似的工作Row_number over.我个人无法看到上面的代码实际上实现了什么,除非我写完全错了.

有什么建议?

hai*_*770 7

按项目类型分组IGrouping<T>,从中可以获得一个密钥和一个IEnumerable<T>分组项目.然后,您可以项目(Select)是为一个匿名类型,使用MinIGrouping<T>x获得每组最低的成本:

items
    .GroupBy(x => x.itemTypeId)
    .Select(x => new { ItemTypeId = x.Key, Cost = x.Min(z => z.cost) })
    .OrderBy(x => x.Cost)
Run Code Online (Sandbox Code Playgroud)


Tim*_*ter 6

你必须分组itemTypeId,然后通过订购组来取最低分cost:

var o = items
    .GroupBy(x => x.itemTypeId)
    .Select(g => g.OrderBy(x => x.cost).First())
    .OrderBy(x => x.cost);
Run Code Online (Sandbox Code Playgroud)