Rem*_*tec 2 c# lambda delegates httpfilecollection
我的代码有这样的东西:
HttpFileCollection files
Run Code Online (Sandbox Code Playgroud)
而不是循环遍历每个文件并将file.ContentLength相加以获得所有内容的总长度,例如
int totalLength = 0;
for (int i = 0; i < files.Count; i++)
{
totalLength += files[i].ContentLength;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用lambda表达式做到这一点所以我有类似的东西..
int totalLength = files.[some sort of delegate here to do the addition].
Run Code Online (Sandbox Code Playgroud)
提前致谢.
编辑:HttpFileCollection有一个GetEnumeratorMethod但是它需要实现IEnumerable来使用lambda表达式吗?
您可以使用LINQ:
int totalLength = files.AllKeys.Select(k => files[k]).Sum(f => f.ContentLength);
Run Code Online (Sandbox Code Playgroud)
不幸的是,HttpFileCollection的枚举器返回字符串的枚举.为了获取实际对象(HttpPostedFile),您需要按键访问"词典".这会将枚举数转换为HttpPostedFile实例的枚举(通过Select),然后对内容长度求和.