问题
I am attempting to list a group of Associations, within each association is a 'widget' that is assigned to the association. The list will include the Association name and any widget assigned to it. The catch is that the inner widget list needs to be sorted by DisplaySequence.
EDMX Model Below:
Simplified Repeater Mark-Up
<asp:Repeater ID="rptAssociations" runat="server">
<ItemTemplate>
<div data-type="assn" id="<%# ((Association)Container.DataItem).AssociationID %>">
<h3 style="margin-top:15px;"><%# ((Association)Container.DataItem).Acronym %> - <%# ((Association)Container.DataItem).Name %></h3>
<asp:Repeater runat="server" ID="rptWidgets" DataSource="<%# ((Association)Container.DataItem).AssociationWidgets %>" >
<HeaderTemplate>
<ul class="WidgetList">
</HeaderTemplate>
<ItemTemplate>
<li id="<%# ((AssociationWidget)Container.DataItem).DisplaySequence %>"><%# ((AssociationWidget)Container.DataItem).Widget.Name %></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
Current Query
var associations = (from a in
context.Associations.Include("AssociationWidgets")
.Include("AssociationWidgets.Widget")
orderby a.Acronym
select a).ToList();
rptAssociations.DataSource = associations;
rptAssociations.DataBind();
I am currently able to get the data that I'm looking for with the setup that I have now. I am looking for the most efficient approach to getting this same data, however, having the Widgets listed in the correct display order.
Is there a different approach to the linq query I should take?
回答1:
I would approach this like this (untested):
var associations =
context.Associations.Select( a =>
new {
//... specific properties you need
AssociationId = a.AssociationId,
Name = a.Name,
... etc
Widgets = a.AssociateWidgets.OrderBy(aw => aw.DisplaySequence)
.Select(aw => aw.Widget)
}
);
Here you'll get a collection of anonymous types. You can use a concrete type such as
public class AssociationInfo
{
public string Name {get;set;}
...
public IEnumerable<Widget> Widgets{ get;set; }
}
if necessary by replacing 'new {'
with 'new AssociationInfo {'
来源:https://stackoverflow.com/questions/15683284/sort-inner-repeater-with-linq-query