문제

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.

다른 팁

You need to cast it, like this:

int totalLength = files.Cast<HttpPostedFile>().Sum(f => f.ContentLength);

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top