Linq返回具有相同(最低)值的所有行

时间:2014-09-15 14:18:32

标签: linq

我有一个linq查询,当前为每个产品返回1个产品详细信息行。

       return ProductDetailView
            .Select() // this is a method in repository
            .Where(x => x.MaxTerm >= days)
            .GroupBy(x => new { ID = x.ProductID })
            .Select(g => g.OrderBy(x => x.MaxTerm).First())
            .OrderBy(x => (x.CostPer100 + x.FeesExcluded))
            .ToList();

此行按产品成本

对订单进行排序
            .OrderBy(x => (x.CostPer100 + x.FeesExcluded))

我想要做的是选择与最低成本具有相同值的所有行 - 换句话说,直到值更改为止所有行。

这在一次查询中是否可行?

1 个答案:

答案 0 :(得分:0)

如果按成本分组,然后对组进行排序,第一组将包含成本最低的所有行:

return ProductDetailView
            .Select() // this is a method in repository
            .Where(x => x.MaxTerm >= days)
            .GroupBy(x => x.ProductID)
            .Select(g => g.OrderBy(x => x.MaxTerm).FirstOrDefault())
            .GroupBy(x => (x.CostPer100 + x.FeesExcluded))
            .OrderBy(g => g.Key)
            .FirstOrDefault()
            .ToList();

但正如Jeff Mercado建议的那样,获得最低成本可能更有效率,然后使用它作为过滤器进行另一次查询。像这样:

var min = ProductDetailView
        .Select() // this is a method in repository
        .Where(x => x.MaxTerm >= days)
        .GroupBy(x => x.ProductID)
        .Select(g => g.OrderBy(x => x.MaxTerm).FirstOrDefault())
        .Min(x => (x.CostPer100 + x.FeesExcluded));

return ProductDetailView
        .Select() // this is a method in repository
        .Where(x => x.MaxTerm >= days && x.CostPer100 + x.FeesExcluded == min)
        .GroupBy(x => x.ProductID)
        .Select(g => g.OrderBy(x => x.MaxTerm).FirstOrDefault())
        .ToList();