代码之家  ›  专栏  ›  技术社区  ›  Anders

可以在循环内利用foreach的LINQ部分吗?

  •  2
  • Anders  · 技术社区  · 17 年前

    我在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>
    <% } %>
    

    是否可以访问我的变量 f 在循环内部,或者是否有其他方法来实现这一点,这样我就不必对 FileInfo(file) ?

    谢谢

    2 回复  |  直到 17 年前
        1
  •  6
  •   dtb    17 年前
    var fileInfos = new DirectoryInfo(path).GetFiles().OrderBy(f => f.Length);
    
    foreach (var fileInfo in fileInfos)
    {
       ...
    }
    
        2
  •  2
  •   John Sheehan    17 年前