列出日期,addHours列出linq

时间:2014-06-24 08:41:40

标签: c# linq list datetime entity

我有列出日期以在网格中显示它,我希望将一小时添加到range2

private void grid_loaded(object sender, RoutedEventArgs e)
{
    var data = new List<EntityViewModel> 
    {
        new EntityViewModel { aDay = new DateTime(1980, 1, 1, 12, 0, 12) },
        new EntityViewModel { aDay = new DateTime(1983, 1, 1, 12, 23, 12) },
        new EntityViewModel { aDay = new DateTime(1985, 6, 14, 12, 0, 12) },
        new EntityViewModel { aDay = new DateTime(1990, 7, 3, 12, 23, 12) },
        new EntityViewModel { aDay = new DateTime(1995, 8, 1, 4,  23, 12) },
        new EntityViewModel { aDay = new DateTime(1996, 1, 1, 12, 0, 12) },
        new EntityViewModel { aDay = new DateTime(2000, 1, 1, 12, 0, 12) },
        new EntityViewModel { aDay = DateTime.Now }
    };

    var range = data.Where(i => i.aDay.Year >= 1983 && i.aDay.Year <= 1996).ToList();
    var range2 = range.Where(i => i.aDay.Date.IsDaylightSavingTime() == true).ToList();
}

我试过了:

var range3 = range.Where(i => i.aDay.Date.IsDaylightSavingTime() == true).ToList();
range3.ForEach(i => i.aDay.AddHours(1));

这样:

foreach (var item in range2.Where(x => x.aDay != null))
{
    item.aDay.AddHours(1);
}

和此:

var range5 = range2.Where(i => i.aDay != null).Select(i => { i.aDay.AddHours(1); return i; }).ToList();

但它什么都不做,总是在同一个小时。

3 个答案:

答案 0 :(得分:4)

AddHours不会改变初始日期,但会返回一个新日期 您需要选择这些日期:

var range5 = range2.Where(i => i.aDay != null).Select(i => i.aDay.AddHours(1));

获取更改日期或

range3.ForEach(i => i.aDay = i.aDay.AddHours(1));

更改列表中项目的日期。

答案 1 :(得分:3)

DateTime是一个结构,所以你必须这样做: var date = DateTime.Now; date = date.AddHours(1);

在你的情况下: range3.ForEach(i => i.aDay = i.aDay.AddHours(1));

答案 2 :(得分:3)

AddHours返回一个新的DateTime,它不会更改当前实例。 http://msdn.microsoft.com/en-us/library/system.datetime.addhours.aspx

for (int i = 0; i < range2.Count; ++i) {
    range2[i].aDay = range2[i].aDay.AddHours(1);
}