【问题标题】:How to perform LINQ OrderBy based on a stringname for column如何根据列的字符串名称执行 LINQ OrderBy
【发布时间】:2011-03-03 11:55:52
【问题描述】:

如果我有

public ActionResult ListExpenseItems(long id)
{
            IQueryable<I_ITEM> expenseItems = er.GetExpenseItems(id);
            return PartialView(expenseItems );
}

和 LINQ

public IQueryable<I_ITEM> GetExpenseItems(long id)
{
            return from i in db.I_ITEM
                   where i.ExpenseId == id
                   orderby i.ExpenseItemId ascending
                   select i;
 }

如果我将一个字符串作为参数传递给 LINQ 方法,比如 "ExpenseTitle",我将如何处理 OrderBy i.ExpenseTitle 以使 orderby 始终与字符串参数匹配?

这种逻辑..但实际上是正确的:

db.I_ITEM.OrderBy(x => (orderBy == 'date') ? x.Date : (orderBy == 'id') ? x.Id : (orderBy == 'cost') ? x.Cost : x.Id);

【问题讨论】:

标签: asp.net-mvc linq


【解决方案1】:

我认为之前的问题可能会解决您的问题

Dynamic LINQ OrderBy

Strongly typed dynamic Linq sorting

或者您可以使用 Dynamic Linq 库。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
相关资源
最近更新 更多