Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ Expression getting rather long

Tags:

c#

linq

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?

like image 932
Jelle Huibregtse Avatar asked Mar 21 '26 10:03

Jelle Huibregtse


1 Answers

In terms of readability and maybe even a little bit performance, I think your code could leverage indexed Enumerable.Select overload and value tuples:

    var tempList = _containers;
    tempList.Add(referenceContainer);
    SortStack(tempList);
    var indexed = tempList.Select((container, index) => (container, index)).ToList();
    foreach (var (container, index) in indexed)
    {
        var weightOnContainer = indexed
            .Where((c, i) => i > index)
            .Sum((c, i) => c.Weight);

        if (weightOnContainer > Container.MaxWeightOnTop)
            return false;
    }

Also in original version .Sum(c => container.Weight) clause looks a little bit funky to me, should not it be .Sum(c => c.Weight)?

like image 149
Guru Stron Avatar answered Mar 23 '26 23:03

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!