linq选择月份之间的日期范围

时间:2012-09-09 11:25:38

标签: c# linq

我列出了以下日期:

List<Datetime> listOfDates = new List<DateTIme>();

listofDates.add(new DateTime(2012,01,04));
listofDates.add(new DateTime(2012,01,05));
listofDates.add(new DateTime(2012,01,06));
..
listofDates.add(new DateTime(2012,01,31));
listofDates.add(new DateTime(2012,02,01));
..
listofDates.add(new DateTime(2012,02,28));
listofDates.add(new DateTime(2012,03,01));
..
listofDates.add(new DateTime(2012,03,16));

我需要按月份范围过滤上面的列表,如下所示:

var filterdListByMonth = listofDates.Where(x.DateTime.Month => 1 and x.DateTime.Month <=2).ToList();

但这似乎没有返回正确的结果。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

如果您修复了编译器错误,它会按预期工作:

List<DateTime> listOfDates = new List<DateTime>();
listOfDates.Add(new DateTime(2012, 01, 04));
listOfDates.Add(new DateTime(2012, 01, 05));
listOfDates.Add(new DateTime(2012, 01, 06));
listOfDates.Add(new DateTime(2012, 01, 31));
listOfDates.Add(new DateTime(2012, 02, 01));
listOfDates.Add(new DateTime(2012, 02, 28));
listOfDates.Add(new DateTime(2012, 03, 01));
listOfDates.Add(new DateTime(2012, 03, 16));
var filterdListByMonth = listOfDates.Where(date => date.Month >= 1 && date.Month <= 2);

// Outputs each date except the two in March.
Console.WriteLine(String.Join(Environment.NewLine, filterdListByMonth));