I have the following classes:
public class Shipment
{
public int Id { get; set; }
public List<Line> Lines { get; set; }
}
public class Line
{
public int Id { get; set; }
public List<Package> Packages { get; set; }
}
public class Package
{
public int Id { get; set; }
public List<Event> Events { get; set; }
}
public class Event
{
//irrelevant properties
}
I also have a dictionary of Events and packageIds:
Dictionary<Event, int> packageEvents; //already populated
I want to match all the package events from the dictionary with their corresponding packages. The code I've written has 3 imbricated foreach statements and therefore the complexity of O(n^3). I would like to transform the code into a smaller statement using Linq and desirably also reduce the complexity.
foreach (var shipment in shipments)
{
foreach (var line in shipment.Lines)
{
if (line.Packages.Any())
{
foreach (var package in line.Packages)
{
var eventsByPackage = packageEvents.Where(x => x.Value == package.Id).Select(x => x.Key);
if (package.Events == null)
{
package.Events = new List<Event>();
}
package.Events.AddRange(eventsByPackage);
}
}
}
}
I would appreciate any suggestion. Thank you in advance.
if (line.Packages.Any())is redundant and can be safely droppedO(n^3)(and theAddRange(eventsByPackage)would make itO(n^4)) but if the outer loops are just groupings of inner elements, then the real complexity can still beO(n)withnbeing the number of events to be processed.