Select Min() 和其他列以及 EF 6 中两列的 GroupBy

Select Min() and other columns and GroupBy by two columns in EF 6

使用下面的示例,(来自此 link 中的答案)我如何 select/group 使用额外的列? 我搜索了这个网站和其他网站并尝试了一些示例,但无法正常工作。

// Existing working code
    public class Rates
        {
            public string RateClass { get; set; }
            public decimal CostDay { get; set; }
            public decimal CostWeek { get; set; }
        }
     var rates = new List<Rates>
                {
                    new Rates {CostDay = 2, CostWeek = 7, RateClass = "Test 1"},
                    new Rates {CostDay = 4, CostWeek = 17, RateClass = "Test 1"},
                    new Rates {CostDay = 6, CostWeek = 27, RateClass = "Test 2"},
                    new Rates {CostDay = 8, CostWeek = 37, RateClass = "Test 2"}
                };
    
                var data = rates.GroupBy(t => t.RateClass)
                    .Select(g => new Rates {
                        RateClass = g.Key,
                        CostDay = g.Min(x => x.CostDay),
                        CostWeek = g.Sum(x => x.CostWeek)
                    })
                    .ToList();

// Need to add one extra column to be selected and grouped on
public class Rates
    {
        public string RateClass { get; set; }
        ****public string TypeOfVehicle { get; set; }****
        public decimal CostDay { get; set; }
        public decimal CostWeek { get; set; }
    }
 var rates = new List<Rates>
            {
                new Rates {CostDay = 2, CostWeek = 7, RateClass = "Test 1",TypeOfVehicle = "A"},
                new Rates {CostDay = 4, CostWeek = 17, RateClass = "Test 1",TypeOfVehicle = "B"},
                new Rates {CostDay = 6, CostWeek = 27, RateClass = "Test 2",TypeOfVehicle = "C"},
                new Rates {CostDay = 8, CostWeek = 37, RateClass = "Test 2",TypeOfVehicle = "D"}
            };

            var data = rates.GroupBy(t => t.RateClass)
                .Select(g => new Rates {
                    RateClass = g.Key,
                    ****TypeOfVehicle = ???**** 
                    CostDay = g.Min(x => x.CostDay),
                    CostWeek = g.Sum(x => x.CostWeek)
                })
                .ToList();

听起来你想要的是:

.GroupBy(g => new { g.RateClass, g.TypeOfVehicle })

然后在.Select()

.Select(g => new Rates 
{
    RateClass = g.Key.RateClass,
    TypeOfVehicle = g.Key.TypeOfVehicle,
    CostDay = g.Min(x => x.CostDay),
    CostWeek = g.Sum(x => x.CostWeek)
})

此分组基于费率 class 和车辆类型的不同组合。