多个linq orderby不工作

时间:2014-01-30 04:10:36

标签: c# linq entity-framework

我有多个OrderBy,但只有第一个订单栏正在运作

public static List<vwData> GetAllData(string startDate, string endDate)
{
    DateTime dtStart = Convert.ToDateTime(startDate).Date;
    DateTime dtEndDate = Convert.ToDateTime(endDate).Date;


    var entities = new DataEntities();
    var query = from c in entities.vwData
                let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
                orderby c.EventCreateDate ascending, c.StartDateTime ascending
                where eventDate >= dtStart && eventDate <= dtEndDate
                select c;
    return query.ToList();
}

3 个答案:

答案 0 :(得分:0)

Orderby应该在条件检查之后,默认排序是升序

var query = from c in entities.vwData
            let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
            where eventDate >= dtStart && eventDate <= dtEndDate
            orderby c.EventCreateDate, c.StartDateTime
            select c;
return query.ToList();

OR

使用Linq,我们可以执行以下操作

var query = entities.vwData.Where(i =>
{
    var eventDate = EntityFunctions.TruncateTime(i.EventCreateDate);
    if (eventDate >= dtStart && eventDate <= dtEndDate)
        return true;

    return false;
})
.OrderBy(j => j.EventCreateDate)
.ThenBy(k => k.StartDateTime)
.Select(m => m);

return query.ToList();

答案 1 :(得分:0)

考虑使用ThenBy

public static List<vwData> GetAllData(string startDate, string endDate)
{
  DateTime dtStart = Convert.ToDateTime(startDate).Date;
  DateTime dtEndDate = Convert.ToDateTime(endDate).Date;


  var entities = new DataEntities();
  var query = from c in entities.vwData
            let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
            orderby c.EventCreateDate ascending
            thenby c.StartDateTime ascending
            where eventDate >= dtStart && eventDate <= dtEndDate
            select c;
  return query.ToList();
}

答案 2 :(得分:0)

尝试以下查询。它会对你有所帮助:

    var query = entities.vwData.Where(i => EntityFunctions.TruncateTime(i.OrderDate) >= dtStart  && EntityFunctions.TruncateTime(i.OrderDate) <= dtEndDate )
        .OrderBy(j => j.EventCreateDate)
        .ThenBy(k => k.StartDateTime)
        .Select(m => m);

   return query.ToList();