我有以下查询要使用投影类名进行排序或过滤:
List<CompanyInfo> list = new List<CompanyInfo>();
using (var db = new DbContext())
{
list.AddRange(
db.Companies.Include("Projects")
.Select(row => new CompanyInfo()
{
ProjectCount = (from s in row.Projects
where s.Company.fId == row.fId
select s.pId).Count(),
Id = satir.fId,
})
//.OrderBy("ProjectCount") //<== what I want to do
);
}
我想使用与ProjectCount
相同的Id
或.OrderBy("ProjectCount")
列来动态订购此查询,例如{{1}}。由于查询结果是IQueryable而不是ObjectContext,因此它不起作用。有没有办法做到这一点?
答案 0 :(得分:1)
你应该能够这样做:.OrderBy(p => p.ProjectCount)
答案 1 :(得分:1)
看一下Dynamic LINQ库 这是tutorial,似乎描述了您的情况。
答案 2 :(得分:1)
如果您知道该怎么做,可以使用LINQ做一些漂亮的事情。也许是这样的事情?
var query = db.Companies.Include("Projects").Select(row =>
new CompanyInfo()
{
ProjectCount = (from s in row.Projects where s.Company.fId == row.fId select s.pId).Count(),
Id = satir.fId,
});
if (orderBy) // orderBy is bool, that tels you what to order by
query = query.OrderBy(x => x.ProjectCount);
else
query = query.OrderBy(x => x.Id);
list.AddRange(query);
答案 3 :(得分:0)
感谢您的回复,我使用了帮助扩展方法: