【问题标题】:Use Linq to move item to bottom of list使用 Linq 将项目移动到列表底部
【发布时间】:2014-01-16 13:16:28
【问题描述】:

这是我的代码:

var list = from c in child_categories orderby c.Translated_Syntax 
           select new { Name = c.Translated_Syntax, ID = c.ID_Category } ;

lst_category.DataSource = list;    
lst_category.DataBind();

我的类别列表是:汽车、其他、儿童、房屋、女孩、表演。

如果我订购我的清单,结果将是:

  • 汽车
  • 儿童
  • 女孩
  • 其他
  • 显示

但我希望将“其他”项目放在列表的底部。 像这样的:

  • 汽车
  • 儿童
  • 女孩
  • 显示
  • 其他

我该怎么做?

【问题讨论】:

    标签: c# asp.net linq


    【解决方案1】:

    你可以使用这个Orderby-"trick":

    from c in child_categories 
    orderby c.Translated_Syntax == "Other", c.Translated_Syntax
    

    您可以记住它是如何工作的:比较返回一个bool,其中true1false0。这就是orderby Translated_Syntax == "Other" 将最后列出“其他”的原因。如果您希望它先于您,则必须反转条件或(更好)使用descending

    【讨论】:

    • 这可以用函数语法来实现吗?
    • @fripp13:当然:var q=child_categories.OrderBy(c => c.Translated_Syntax == "Other").ThenBy(c => c.Translated_Syntax)
    猜你喜欢
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2018-04-25
    • 1970-01-01
    相关资源
    最近更新 更多