Home > OS >  Select Min() on GroupBy in EF 6 Net Core 5
Select Min() on GroupBy in EF 6 Net Core 5

Time:09-23

In a table grouped by "RateClass" I am trying to select "RateClass", Min("CostDay") and "CostWeek", but my code crashs.

var data = db.Rates.GroupBy(t => t.RateClass)
             .Select( g => new {  
                                rateClass = g.Select(x => x.RateClass), 
                                costtDay = g.Min(x => x.CostDay), 
                                costWeek = g.Select(x => .CostWeek)
                               })
              .ToList();

CodePudding user response:

As I stated in the comment, it won't compile as you're missing an x here costWeek = g.Select(x => .CostWeek), should be costWeek = g.Select(x => x.CostWeek)

Also, are you trying to create an entry for each group? if so, you could try this...

 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();

The RateClass will be the Key you're grouping on, and I just summed the CostWeek as an example. Here's a link to try it.

  • Related