是否可以在循环内使用foreach的LINQ部分?

And*_*ers 2 c# asp.net-mvc

我在ASP.NET MVC应用程序中有这个视图:

<%
    var path = Path.Combine(HttpRuntime.AppDomainAppPath, "uploads"); 
    foreach (var file in Directory.GetFiles(path).OrderBy(f => new FileInfo(f).Length))
    {
        var item = new FileInfo(file);
%>
<tr>
    <td></td>
    <td>
        <%=Html.Encode(Path.GetFileName(item.Name))%>
    </td>
    <td>
        <%=Html.Encode(Functions.FormatBytes(item.Length))%>
    </td>
    <td>
        <%=Html.FileLink(item.Name)%>
    </td>
</tr>
<% } %>
Run Code Online (Sandbox Code Playgroud)

是否有可能f在循环中访问我的变量,或者是否有其他方法来执行此操作,因此我不必维度两个实例FileInfo(file)?

谢谢!

dtb*_*dtb 6

var fileInfos = new DirectoryInfo(path).GetFiles().OrderBy(f => f.Length);

foreach (var fileInfo in fileInfos)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)