0

I have this piece of code that works:

        var mealsAndSchoolsPerformance = new List<MealsAndSchoolPerformanceUI>();

        foreach (SchoolModel sc in schoolData.Where(s => s.IsHidden == false))
        {
            var mealAndSchoolP = new MealsAndSchoolPerformanceUI
            {
                Id = sc.Id,
                SchoolName = sc.SchoolName,
                Week = DateExtensions.GetIso8601WeekOfYear(startDate, true),
                TotalFoodSpent = foodSpend.ContainsKey(sc.Id) ? foodSpend[sc.Id] : 0,
                TotalHours = totalHours.ContainsKey(sc.Id) ? totalHours[sc.Id]: 0,
                MealsKs1 = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.KeyStage1).Sum(s => s.MealNo), 
                MealsKs2 = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.KeyStage2).Sum(s => s.MealNo), 
                MealsNursery = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Nursery).Sum(s => s.MealNo), 
                MealsStaff = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Adult).Sum(s => s.MealNo),
                MealsSenior = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Senior).Sum(s => s.MealNo),
                TotalSales = meals.Where(m => m.SchoolId == sc.Id).Sum(m => m.TotalPrice),
                TotalInvoicePrice = meals.Where(m => m.SchoolId == sc.Id).Sum(m => m.TotalInvoicePrice),
                Region = sc.SchoolLead?.AddressRegion ?? " ",
                SchoolGroup = sc.SchoolGroups.FirstOrDefault()?.GroupName ?? "",
                Manager = sc.ManagerUser?.FullName ?? "",
                ServiceStarted = sc.ServiceStarted,
                RollNoNursery = sc.RollNoNursery ?? 0,
                RollNoSchool = sc.RollNoSchool ?? 0,
                ServingDays = MealBL.MealServingDays(sc.Id, startDate, startDate.AddDays(6))
            };
            mealsAndSchoolsPerformance.Add(mealAndSchoolP);
        }

question is: is there any way of initialising the list and each object at the same time in order to improve performance? something like

var mealsAndSchoolsPerformance = new List();

2
  • You know Where so I guess you also know Select. Commented Oct 12, 2017 at 9:30
  • this object gets the data from several objects, so I'm having issues at combining them
    – Iria
    Commented Oct 12, 2017 at 9:49

2 Answers 2

1

There is no way to initialize a list and multiple objects "at the same time". Linq can make your code shorter but under the hood it will foreach over the data just the same.

But you can improve performance: you're executing the meals.Where(m => m.SchoolId == sc.Id) part multiple times, while you could do this once and hang on to the result:

foreach (SchoolModel sc in schoolData.Where(s => s.IsHidden == false))
{
    var schoolMeals = meals.Where(m => m.SchoolId == sc.Id).ToArray();
    ...
    TotalSales = schoolMeals.Sum(m => m.TotalPrice),
    TotalInvoicePrice = schoolMeals.Sum(m => m.TotalInvoicePrice),

Furthermore you're running similar InvoiceMealType queries over the same data, where you could do this in a single pass:

foreach (SchoolModel sc in schoolData.Where(s => s.IsHidden == false))
{
    var schoolMeals = meals.Where(m => m.SchoolId == sc.Id);
    var byInvoiceMealType = schoolMeals.ToLookup(m => m.InvoiceMealType);
    ...
    MealsKs1 = byInvoiceMealType[InvoiceMealType.KeyStage1].Sum(s => s.MealNo),

Perhaps this was not the answer you were hoping to get - and how much performance is gained depends on the source and amount of data.

0

You can use PLINQ from Task Parallel Library to initialize objects on multiple threads at once, giving you performance boost on multi-core processors. This assumes that data sources used in object initialization, such as foodSpend and meals, are thread-safe for reading and enumeration (I cannot tell if it is the case without knowing types of these objects, but Dictionary<T>, List<T> and arrays are safe to be used this way, for other types you will have to check thread safety yourself).

var mealsAndSchoolsPerformance = schoolData
    .Where(s => s.IsHidden == false)
    .AsParallel()//This causes that following query will run on multiple threads
    .Select(sc => new MealsAndSchoolPerformanceUI
        {
            Id = sc.Id,
            SchoolName = sc.SchoolName,
            Week = DateExtensions.GetIso8601WeekOfYear(startDate, true),
            TotalFoodSpent = foodSpend.ContainsKey(sc.Id) ? foodSpend[sc.Id] : 0,
            TotalHours = totalHours.ContainsKey(sc.Id) ? totalHours[sc.Id]: 0,
            MealsKs1 = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.KeyStage1).Sum(s => s.MealNo), 
            MealsKs2 = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.KeyStage2).Sum(s => s.MealNo), 
            MealsNursery = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Nursery).Sum(s => s.MealNo), 
            MealsStaff = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Adult).Sum(s => s.MealNo),
            MealsSenior = meals.Where(m => m.SchoolId == sc.Id).Where(m => m.InvoiceMealType == InvoiceMealType.Senior).Sum(s => s.MealNo),
            TotalSales = meals.Where(m => m.SchoolId == sc.Id).Sum(m => m.TotalPrice),
            TotalInvoicePrice = meals.Where(m => m.SchoolId == sc.Id).Sum(m => m.TotalInvoicePrice),
            Region = sc.SchoolLead?.AddressRegion ?? " ",
            SchoolGroup = sc.SchoolGroups.FirstOrDefault()?.GroupName ?? "",
            Manager = sc.ManagerUser?.FullName ?? "",
            ServiceStarted = sc.ServiceStarted,
            RollNoNursery = sc.RollNoNursery ?? 0,
            RollNoSchool = sc.RollNoSchool ?? 0,
            ServingDays = MealBL.MealServingDays(sc.Id, startDate, startDate.AddDays(6))
        })
    .ToList();

This performace improvement does not exclude those suggested by @C.Evenhuis, so for best performance, you should combine them together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.