【问题标题】:Sorting optimization for date日期排序优化
【发布时间】:2018-08-11 05:04:16
【问题描述】:
I have been sorting a collection like this. i was wondering whether it can be optimized or not. please have a look:

//ordering elements i.e latest ToDate will be on top and if ToDate are same then latest FromDate will be in top
var posistions = (someModel.Positions.OrderByDescending(x => x.ToDate)
    .ThenByDescending(x => x.FromDate).Where(x => !x.ToDate.HasValue).ToArray())
    .Concat(someModel.Positions.OrderByDescending(x => x.FromDate)
    .ThenByDescending(x => x.ToDate).Where(x => x.ToDate.HasValue).ToArray());

someModel.Positions = posistions.ToArray();

【问题讨论】:

  • 为什么要连接列表?也就是说,如果 Todate 没有值,那么它们应该排在最后,但是按 fromDate 排序?
  • 首先我想,因为我是通过descend来订购ToDate,如果没有ToDate,它将移动到concat之后写入的块。你猜对了
  • 第一个优化是不要将 10 个 LINQ 命令链接在一起。

标签: c# arrays linq sorting


【解决方案1】:

你可能只是做这样的事情。我不确定您需要订购什么极性,但它很容易改变

var positions = model.Positions
                     .OrderByDescending(x => x.ToDate.HasValue)
                     .ThenByDescending(x => x.ToDate)
                     .ThenByDescending(x => x.FromDate);

foreach (var pos in positions)
   Console.WriteLine(pos.ToDate+" : " + pos.FromDate);    

输出

8/8/2018 5:34:49 AM : 8/8/2018 5:34:49 AM
8/7/2018 5:34:49 AM : 7/2/2018 5:34:49 AM
8/6/2018 5:34:49 AM : 6/22/2018 5:34:49 AM
null : 8/1/2018 5:34:49 AM
null : 7/22/2018 5:34:49 AM

Full Demo Here

【讨论】:

    【解决方案2】:

    见小提琴:https://dotnetfiddle.net/nNbT5D

    对已接受答案的小调整:

    .OrderBy(x => x.ToDate ?? DateTime.MinValue)
    .ThenByDescending(x => x.FromDate);
    

    这段代码足以复制结果。

    使用此排序标准查看结果

    From: 8/4/2018 7:35:00 AM ========= ToDate: 
    From: 7/25/2018 7:35:00 AM ========= ToDate: 
    From: 6/25/2018 7:35:00 AM ========= ToDate: 8/9/2018 7:35:00 AM
    From: 7/5/2018 7:35:00 AM ========= ToDate: 8/10/2018 7:35:00 AM
    From: 8/11/2018 7:35:00 AM ========= ToDate: 8/11/2018 7:35:00 AM
    
     result using question's sorting criteria below
    From: 8/4/2018 7:35:00 AM ========= ToDate: 
    From: 7/25/2018 7:35:00 AM ========= ToDate: 
    From: 8/11/2018 7:35:00 AM ========= ToDate: 8/11/2018 7:35:00 AM
    From: 7/5/2018 7:35:00 AM ========= ToDate: 8/10/2018 7:35:00 AM
    From: 6/25/2018 7:35:00 AM ========= ToDate: 8/9/2018 7:35:00 AM
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-17
      • 2020-06-23
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多