Home > Software design >  Select Min() and other columns and GroupBy by two columns in EF 6
Select Min() and other columns and GroupBy by two columns in EF 6

Time:09-25

Using the example below, (from the answer in this link here) how can I select/group with an extra column ? I have searched this site and others and tried some examples but couldn't get it to work.

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

CodePudding user response:

It sounds like what you want would be:

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

Then in the .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)
})

This groups on distinct combinations of rate class and vehicle type.

  • Related