如果Linq查询中的语句

时间:2013-07-18 18:15:39

标签: c# asp.net sql linq

我正在尝试对dropdownlist进行排序,只是在选择了特定的id时才将其输入到数据库中。否则我希望它们按升序排序。我不确定如何在选择特定Id时添加不对列表进行排序的最终组件。这是我到目前为止的地方:

var items = (from p in _db.Funds
                     where p.DesignationId == id
                     orderby p.Name ascending 
                     select new { p.id, p.Name });
        return items;

2 个答案:

答案 0 :(得分:8)

你的意思是这样的吗?

var items = 
    (from p in _db.Funds
     where p.DesignationId == id
     select new { p.id, p.Name });
if (id != "some id")
{
    items = items.OrderBy(p => p.Name);
}

return items.ToList();

答案 1 :(得分:2)

这将是一个解决方案

var items = (from p in _db.Funds
                 where p.DesignationId == id
                 orderby p.id == "the id" ? p.Name : null 
                 select new { p.id, p.Name });
return items;