LINQ to SQL lambda exp.OrderBy,Case When,Dynamic Where

Rog*_*Dai 2 c# lambda case linq-to-sql

我正在使用LINQ to SQL和LINQ动态在哪里和顺序.

我想将下面的代码(ASP)转换为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
Run Code Online (Sandbox Code Playgroud)

这是我的查询:

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;
Run Code Online (Sandbox Code Playgroud)

上面的例子不起作用!,任何想法,如果它可能吗?还有其他办法吗?

谢谢

Jon*_*eet 8

我建议您直接使用和方法Where,OrderBy而不是尝试使用查询表达式ThenByDescending.例如:

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);
Run Code Online (Sandbox Code Playgroud)

请注意使用ThenByDescending而不是OrderByDescending- 您的原始查询使用两个"主要"排序,这几乎不是您想要的.

我不完全确定该OrderBy条款是否有效,但值得一试.如果它不起作用,请说出会发生什么,而不只是说"它不起作用".