Calculate total content length of HttpFileCollection using Lambda expressions

2.6k views Asked by At

My code has something like this:

HttpFileCollection files

Instead of looping through each file and adding up the file.ContentLength to get the total length of all content e.g.

        int totalLength = 0;
        for (int i = 0; i < files.Count; i++)
        {
            totalLength += files[i].ContentLength;
        }

Is there a way I can do this with a lambda expression so I have something like..

int totalLength = files.[some sort of delegate here to do the addition].

Thanks in advance.

Edit: HttpFileCollection has a GetEnumeratorMethod but would it need to implement IEnumerable to use a lambda expression?

2

There are 2 answers

7
Reed Copsey On BEST ANSWER

You could use LINQ:

int totalLength = files.AllKeys.Select(k => files[k]).Sum(f => f.ContentLength);

Unfortunately, HttpFileCollection's enumerator returns an enumeration of strings. In order to get the actual objects (HttpPostedFile), you need to access the "dictionary" by key. This converts the enumerator to an enumeration of HttpPostedFile instances (via Select), then sums the content length.

2
Erik van Brakel On

To add to the accepted answer, indeed, you can use this:

int totalLength = files.AllKeys.Select(k => files[k]).Sum(f => f.ContentLength);

The reason why you don't have to enumerate in your code is because the Sum extension method does that for you. If you run it through Reflector you eventually find this bit of code:

public static int Sum(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    int num = 0;
    foreach (int num2 in source)
    {
        num += num2;
    }
    return num;
}

As you see ,it's not really rocketscience. It's almost the same as your original code even!

Note: If you want to find this code, crack open System.Core, go to the System.Linq namespace and open the Enumerable class definition. You'll find these methods here (among other places I think).