Can the LINQ part of foreach be used inside a loop?

I have this view in an ASP.NET MVC application:

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

      

Is it possible to access my variable f

inside the loop, or is there some other way to do it so I don't need to measure two instances FileInfo(file)

?

Thank!

+2


source to share


2 answers


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

foreach (var fileInfo in fileInfos)
{
   ...
}

      



+6


source


Your opinion really trumps his responsibilities here. You have to create a class that maps the data you want to display in the view, then in your controller, retrieve the data and populate the IEnumerable <> of your classes and return it to the ViewModel, which can look like your simple view through.



+2


source







All Articles