2011-03-17 183 views
2

我正在使用LINQ to SQL和LINQ dynamic where和order by。LINQ to SQL lambda exp。 OrderBy,Case When,Where Where

我想将下面的代码(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 

这里是我的查询:

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; 

上面的例子不工作! ,任何想法,如果可能的话?任何其他方式来做到这一点?

感谢

回答

7

而不是试图用一个查询表达式,我建议你直接使用WhereOrderByThenByDescending方法。例如:

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); 

注意使用ThenByDescending代替OrderByDescending - 原始查询用了两个“第一”排序这是几乎从来没有你想要的东西。

我并不完全确定OrderBy条款会起作用,但值得一试。如果它没有工作,请说出发生了什么,而不是仅仅说“它不工作”。

+0

您好!你是一个帮助我解决数十亿问题的史诗家伙。谢谢! ('OrderBy'子句工作得很好..) – 2013-09-16 12:30:48