2

早些时候我发布了排序日期和时间的问题。mipe34回答了它,但我一直试图在我的代码中使用该解决方案。

这是我到目前为止所做的。我创建了一个类,如下所示:

public class Meals
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

在我的主类中,我有以下具有日期对值的方法:

 IList<DateTime> starts = new List<DateTime>();
            IList<DateTime> ends = new List<DateTime>();
            DateTime breakStart1 = new DateTime(2012, 02, 15, 12, 30, 00);  // 15/02/12 12.30PM
            DateTime breakEnd1 = new DateTime(2012, 02, 15, 13, 30, 00);  // 15/02/12 01.30PM
            DateTime breakStart2 = new DateTime(2012, 02, 15, 11, 00, 00);  // 15/02/12 11.00AM
            DateTime breakEnd2 = new DateTime(2012, 02, 15, 12, 00, 00);  // 15/02/12 12.00PM
            DateTime breakStart3 = new DateTime(2012, 02, 15, 12, 00, 00);  // 15/02/12 12.00PM
            DateTime breakEnd3 = new DateTime(2012, 02, 15, 01, 00, 00);  // 15/02/12 01.00PM
            starts.Add(breakStart1);
            starts.Add(breakStart2);
            starts.Add(breakStart3);
            ends.Add(breakEnd1);
            ends.Add(breakEnd2);
            ends.Add(breakEnd3);
            for (int i = 0; i < starts.Count; i++)
            {
                var breaks = new List<Break>()


             {
                 //for (int j= 0; j<starts.Count; j++)
                 //{
                 new Break()
                     {
                         MealStart = starts[i],
                         MealEnd = ends[i]

                     }
                // }
             };

                var ordered = breaks.OrderBy(s => s.MealStart);
                foreach (var ord in ordered)
                {
                    System.Console.WriteLine(ord.MealStart);
                    System.Console.WriteLine(ord.MealEnd);
                }
            }

我怎样才能传递我所有的日期对并使用他的解决方案?它不会带回预期值。

4

1 回答 1

1

首先创建对象并将它们添加到列表中。在这种情况下,您可以使用集合初始化程序。

var mealList = new List<Meals>
{
     new Meals { Start = dtmealStart1, End = dtmealStart1 },
     /* Repeat for the rest of them possibly incorporating some kind of loop to generate this list */
};

//and then get your sorted list
var sortedMealList = mealList.OrderBy(m => m.Start);
于 2013-02-27T00:36:58.327 回答