So, I have a list of objects (containers) in my code and I want to check if the container I will add, will contribute to the maximum weight on top of each container (container.MaxWeightOnTop). I have created this function:
private bool TooMuchWeight(Container referenceContainer)
{
var tempList = _containers;
tempList.Add(referenceContainer);
SortStack(tempList);
foreach (var container in tempList)
{
var index = tempList.FindIndex(c => c == container);
var weightOnContainer = tempList.Where(c => tempList.FindIndex(i => i == container) > index)
.Sum(c => container.Weight);
if (weightOnContainer > Container.MaxWeightOnTop)
return false;
}
return true;
}
As you can see it gets rather long, my IDE even suggest this LINQ expression for the entire foreach loop:
return (from container in tempList
let index = tempList.FindIndex(c => c == container)
select tempList.Where(c => tempList.FindIndex(i => i == container) > index)
.Sum(c => container.Weight)).All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);
Even when I use the .GetRange function it still remains long:
return tempList
.Select(container =>
tempList.GetRange(tempList.FindIndex(c => c == container), Length).Sum(c => c.Weight))
.All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);
Question: Is it possible to compress this expression?