我有一个活动日历。我使用以下LINQ语句加载事件以显示在日历中:
var events = CalendarItems?.GroupBy(e => e.StartDate);
这会导致GroupedEnumerable具有如下键/值:
Key = 6/26/2019, Value = CalendarItem
Key = 7/10/2019, Value = CalendarItem
Key = 7/18/2019, Value = CalendarItem
某些CalendarItems具有“ EndDate”,如果确实如此,我希望StartDate到EndDate范围内的每个日期也都包含在结果集中。因此,如果7/18/2019 CalendarItem的EndDate为7/20/2019,则我的结果集还将包含以下2个项目:
Key = 7/19/2019, Value = CalendarItem
Key = 7/20/2019, Value = CalendarItem
我不知道如何修改LINQ语句。有什么建议吗?
谢谢!
因此,如果我有以下两个CalendarItems:
StartDate = 7/8/2019, EndDate = null
StartDate = 7/18/2019, EndDate = 7/20/2019
那么我的结果应该是:
Key = 7/8/2019, Value = CalendarItem
Key = 7/18/2019, Value = CalendarItem
Key = 7/19/2019, Value = CalendarItem
Key = 7/20/2019, Value = CalendarItem
答案 0 :(得分:1)
尝试一下:
var events = CalendarItems?.Where(x => x.EndDate.HasValue && x.StartDate < x.EndDate).GroupBy(e => e.StartDate);
(对于第一次检查,您也可以进行x.EndDate != null
)
要注意的最大事情就是.Where()
子句。您也可以在遍历组时执行此操作。因此,如果您需要在分组后进行检查,则可以选择以下方式:
var events = CalendarItems?.GroupBy(e => e.StartDate);
foreach(var event in events)
{
var validEvent = event.Where(x => x.EndDate.HasValue && x.StartDate < x.EndDate);
}
从功能上讲,它们是相同的,但是如果出于任何原因需要处理其他日期,则foreach()
将允许您逐组选择需要的日期。
答案 1 :(得分:0)
class Item
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
}
var items = new List<Item>
{
new Item {StartDate = new DateTime(2019, 2, 22)},
new Item {StartDate = new DateTime(2019, 3, 12 )},
new Item {StartDate = new DateTime(2019, 4, 15), EndDate = new DateTime(2019, 4, 25) },
new Item {StartDate = new DateTime(2019, 2, 15), EndDate = new DateTime(2019, 2, 17) },
new Item {StartDate = new DateTime(2019, 2, 23)},
new Item {StartDate = new DateTime(2019, 2, 7)},
};
var x = items.Select(i => (i.StartDate, diff: Enumerable.Range(0, ((i.EndDate == null ? i.StartDate : i.EndDate).Value - i.StartDate).Days + 1)))
.Select(x => x.diff.Select(z => x.StartDate.AddDays(z)));
var days = new List<DateTime>();
x.ToList().ForEach(dates => days.AddRange(dates));
// Output:
days.OrderBy(i => i).ToList().ForEach(d => Console.WriteLine(d.ToShortDateString()));
/*
Output:
07.02.2019
15.02.2019
16.02.2019
17.02.2019
22.02.2019
23.02.2019
12.03.2019
15.04.2019
16.04.2019
17.04.2019
18.04.2019
19.04.2019
20.04.2019
21.04.2019
22.04.2019
23.04.2019
24.04.2019
25.04.2019
*/