Sort Inner Repeater with LINQ query

强颜欢笑 提交于 2019-12-10 15:54:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!