I'm using LINQ to SQL and LINQ dynamic where and order by.
I want to convert the code below(ASP) to C#.net.
function getTestimonialList(statusCd)
sWhere = ""
if statusCd <> "" then
sWhere = " where status='" & statusCd & "'"
end if
sqlStr="select * from testimonial" & sWhere & " order by case when status = 'P' then 1 when status = 'A' then 2 else 3 end, dateadded desc"
set rs=getResult(sqlStr)
set getTestimonialList=rs
end function
Here is my query :
var TestimonialList = from p in MainModelDB.Testimonials
where String.IsNullOrEmpty(statusCd)?"1=1":p.status== statusCd
orderby p.status == 'P' ? 1 : (p.status == 'A' ? 2 : 3)
orderby p.DateAdded descending
select p;
the above example doesn't work! , any idea if its possible? any other way to do it?
Thanks
Instead of trying to use a query expression, I suggest you use the Where
, OrderBy
and ThenByDescending
methods directly. For example:
IQueryable<Testimonial> testimonials = MainModelDB.Testimonials;
if (!string.IsNullOrEmpty(statusCd))
{
testimonials = testimonials.Where(t => t.status == statusCd);
}
var ordered = testimonials.OrderBy(t => t.status == 'P' ?
1 : (t.status == 'A' ? 2 : 3))
.ThenByDescending(t => t.DateAdded);
Note the use of ThenByDescending
instead of OrderByDescending
- your original query used two "primary" orderings which is almost never what you want.
I'm not entirely sure that the OrderBy
clause will work, but it's worth a try. If it doesn't work, please say what happens instead of just saying "it doesn't work".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.