【问题标题】:Can I define Default Sort order in LinQ我可以在 LinQ 中定义默认排序顺序吗
【发布时间】:2009-03-26 19:02:50
【问题描述】:

如果我有一个嵌套的 ListView,并且我在 LinQ 中调用了一个相关的表,我如何对其进行排序,而不求助于父级的 ItemDataBound 事件?

伪代码(已更新解决方案):

<asp:ListView ID="lv" runat="server" OnItemDataBound="lv_ItemDataBound" >
   <LayoutTemplate>
      <!-- Product Category Stuff --> 
      <asp:PlaceHolder Id="itemPlaceholder" runat="server"></asp:PlaceHolder>
   </LayoutTemplate>

   <ItemTemplate>
      <asp:ListView ID="lvInner" runat="server" DataSource='<%# <%# ((Category)Container.DataItem).Products.OrderBy(p => p.Description) %> %>'>
         <LayoutTemplate>
            <ul>
               <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
            </ul>
         </LayoutTemplate>
         <ItemTemplate>
            <li>Item Stuff</li>
         </ItemTemplate>
      </asp:ListView>
   </ItemTemplate>
</asp:ListView>

也许该方法看似简单,但我希望内部 Products 按字段排序。如果我没记错的话,我看不到以声明方式执行此操作的方法,因为 LinQ 会动态创建此查询,并且不进行排序。

有什么想法吗?

更新

将示例更新为以下内容:

<%# ((Category)Container.DataItem).Products.OrderBy(p => p.Description) %>

希望对其他人有所帮助!

【问题讨论】:

    标签: asp.net linq sorting listview nested


    【解决方案1】:

    我的假设是 Products 是 IEnumerable&lt;Product&gt;(或 IQueryable)。如果是这样,为什么不直接将 OrderBy 方法添加到评估中,如下所示:

    <%# Eval("Products.OrderBy(p => p.FieldToSortOn)") %>
    

    【讨论】:

    • 这听起来可能很愚蠢......但我什至没有想到......或者更准确地说......我没有意识到你可以做到这一点。谢谢。立即测试。
    • 乍一看,这似乎是不可能的。我真的可以使用 Eval 来评估字符串表达式吗?我收到此错误:DataBinding: 'OrderBy(p => p' is not a valid indexed expression.
    • 明白了!同样的想法,但我是通过以下方式做到的: p.Description) %> 似乎有效!
    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多