Is there a LINQ way of converting a generic list of objects to an X by Y matrix of the same type?
I have a generic list of objects, for example: List<Photo>
and want to convert this to something I can use on an MVC view.
In the form (basic example):
<% foreach (var row in PhotoList) { %>
开发者_JAVA技巧
// Render Matrix (using photo properties)
<tr>
<% foreach(photo in row) { %>
<td><%=photo.Name%></td>
<% } %>
</tr>
<% } %>
I have thought of doing this manually, using something like List<List<Photo>>()
, but is there a nifty way of doing this using LINQ? Supplying the number of columns, rows and page a paged Matrix Display, or other better ideas.
You could create a matrix using GroupBy()
given the number of columns x
you want:
photos.Select( (photo, index) => new { Index = index, Photo = photo })
.GroupBy( n=> n.Index / x)
.Select( g => g.Select( p=> p.Photo).ToList())
.ToList();
The result is a List<List<Photo>>
with x
photos in each inner list. You should then just be able to use two foreach loops to render them (as in your example).
精彩评论