使用 Lambda 表达式计算 HttpFileCollection 的总内容长度
我的代码有这样的内容:
HttpFileCollection files
而不是循环遍历每个文件并添加 file.ContentLength 来获取所有内容的总长度,例如
int totalLength = 0;
for (int i = 0; i < files.Count; i++)
{
totalLength += files[i].ContentLength;
}
有没有一种方法可以使用 lambda 表达式来做到这一点,所以我有类似的东西..
int totalLength = files.[some sort of delegate here to do the addition].
谢谢进步。
编辑:HttpFileCollection 有一个 GetEnumeratorMethod 但是否需要实现 IEnumerable 才能使用 lambda 表达式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 LINQ:
不幸的是,HttpFileCollection 的枚举器返回字符串的枚举。为了获取实际的对象(HttpPostedFile),您需要通过键访问“字典”。这会将枚举器转换为 HttpPostedFile 实例的枚举(通过 Select),然后对内容长度求和。
You could use LINQ:
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.
事实上,要添加到已接受的答案中,您可以使用以下方法:
您不必在代码中进行枚举的原因是因为 Sum 扩展方法可以为您执行此操作。如果您通过 Reflector 运行它,您最终会发现这段代码:
如您所见,这并不是真正的火箭科学。它甚至与您的原始代码几乎相同!
注意:如果您想找到此代码,请破解打开 System.Core,转到 System.Linq 命名空间并打开 Enumerable 类定义。您可以在这里找到这些方法(我认为还有其他地方)。
To add to the accepted answer, indeed, you can use this:
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:
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).