开发者

Calculate total content length of HttpFileCollection using Lambda expressions

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?


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜