Linq获取具有列的最小值但基于另一列值的行

Linq to get row with a minimum value of a column but based on another column value

我看过相关的问题和答案,但其中 none 帮助了我。 我创建了一个 linq 查询来获取这样的 IEnumerable 列表 -

**price**     **car_name**    **location**
  23              carA          locationA
  43              carA          locationB
  56              carA          locationC
  12              carB          locationA
  34              carB          locationB
  46              carB          locationC

现在我只想要每辆车最低价格的行... 提前致谢。

编辑:抱歉,我不清楚我的问题,但我也想要所有位置...我在单独的下拉列表中显示。

from cs in myContext.CarStore
group cs by cs.car_name into cgroup
 select new {
        Car_Name= cgroup.Key,
        Price= cgroup.Min(cs=> cs.price)});

我认为这可能有帮助..

您需要根据车名对 Collection 进行分组,然后按价格对每组进行排序,这样您就可以得到最小值。

var result = carList.GroupBy(x=>x.Name)
                     .Select(x=>x.OrderBy(p=>p.Price).First());

如果你想避免Order By,你可以使用Aggregate。

var result = list.GroupBy(x => x.Name)
        .Select(g => g.Aggregate((c1, c2) => c1.Price < c2.Price ? c1 : c2));

聚合只会在 collection 上迭代一次,以最低价格跟踪汽车。

无论哪种情况,输出样本,

其他人提出了将您的汽车分组到具有相同 CarName 的组中的想法。然后他们对每组中的所有 CarPrices 进行排序,然后他们采用 FirstOrDefault CarPrice。

如果您只想要最小的 CarPrice,那么订购所有 CarPrices 有点浪费

为此我使用 GroupBy overload with KeySelector, ElementSelector and ResultSelector

var cheapestCars = allCars.GroupBy(

    // key selector:
    car => car.CarName,

    // element selector
    car => car.CarPrice,

    // result selector:
    (carName, pricesOfCarsWithThisCarName) => new
    {
        CarName = carName,
        LowestAvailablePrices = pricesOfCarsWithThisCarName.Min(),
    });