【问题标题】:Why isn't my List<t> sort working?为什么我的 List<t> 排序不起作用?
【发布时间】:2013-02-08 15:03:04
【问题描述】:

我有一个列表,我需要在处理它之前按日期开始。这是父记录的子记录

 public class DayRequested
 {
    public int RequestId { set; get; }
    public string DateOfLeave { get; set; }

    public static int CompareDateOfLeave(DayRequested d1, DayRequested d2)
    {
        return d1.DateOfLeave.CompareTo(d2.DateOfLeave);
    }
 }

在我的控制器中,我首先对其进行排序,然后再对其进行处理。以下是我尝试过的所有方法。请注意,当我第一次尝试时,未注释的那个起作用了。这些都没有改变列表的顺序。

        //List<DayRequested> requestedDays = requestedDaysIn.OrderBy(o => o.DateOfLeave).ToList();

        requestedDays = requestedDays.OrderBy(o => o.DateOfLeave).ToList();

        //Comparison<DayRequested> comp = new Comparison<DayRequested>(DayRequested.CompareDateOfLeave);
        //requestedDays.Sort(comp);

        //requestedDays.Sort(delegate(DayRequested a, DayRequested b)
        //{
        //    return a.DateOfLeave.CompareTo(b.DateOfLeave);
        //});

        DateTime nextFirstDay = Convert.ToDateTime(requestedDays.First().DateOfLeave);

在我的列表中,我有:

1, 07/10/2013, other info here
1, 07/10/2013, other info here
1, 07/12/2013, other info here
1, 07/12/2013, other info here
1, 07/08/2013, other info here
1, 07/08/2013, other info here

我可能做错了什么?我需要按日期顺序列出的列表,以便我可以按正确的顺序正确运行一些后端进程。

【问题讨论】:

  • @varesa:这个问题与那个无关。
  • 我刚刚更仔细地阅读了另一个 Q,并注意到了同样的问题。起初我没有看到另一个问题是关于排序排序的项目......
  • 我要说的是,我昨天花了 3 个小时在互联网上搜索它为什么不起作用。从未见过字符串。

标签: asp.net-mvc-3 list sorting


【解决方案1】:

您的DateOfLeave 属性是一个字符串,并且可能以这种形式存储:

7/10/2013
7/8/2013
7/12/2013

如果将它们按字符串排序,则 7/10 会在 7/8 之前,因为“1”小于“8”。要解决此问题,请将您的属性设为 aDateTime 或在进行排序之前对其进行转换。

【讨论】:

  • 我完全错过了。 :-/ 感谢您指出了这一点。我在排序前转换为DateTime。现在可以了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2017-09-14
  • 2012-08-08
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多