有兩種簡單的方法從Period
類轉換日期,日期的一個列表。你可以擴展Period
類來給你日期並使用linq來壓扁它,或者你用linq讀取兩個屬性。如果SingleDate
類真的只存儲日期而沒有其他功能,並且它沒有提供任何附加功能,則可以考慮只提取日期。
// Test data.
var periods = new[]
{
new Period(new DateTime(2014, 01, 01), new DateTime(2014, 04, 30)),
new Period(new DateTime(2014, 05, 01), new DateTime(2014, 07, 31)),
new Period(new DateTime(2014, 08, 01), new DateTime(2014, 09, 30)),
};
如果你可以讓Period
類來實現IEnumerable<DateTime>
接口,從而拉平爲您的日期,然後簡單SelectMany
可用於:
var result1 =
periods
// The Period class will enumerate the dates for SelectMany:
.SelectMany(x => x)
// Uncomment this line if you want to encapsulate the date.
//.Select(x => new SingleDate() { Date = x })
.ToList();
否則,你就必須彙整裏面的Period
日期SelectMany
:
var resul2 =
periods
// Here SelectMany has to enumerate the dates:
.SelectMany(x => new[]
{
x.PeriodStart,
x.PeriodEnd
})
// Uncomment this line if you want to encapsulate the date.
//.Select(x => new SingleDate() { Date = x })
.ToList();
Period
-class實現在IEnumerable<DateTime>
接口來枚舉日期:
public class Period : IEnumerable<DateTime>
{
public Period(DateTime firstDay, DateTime lastDay)
{
this.PeriodStart = firstDay;
this.PeriodEnd = lastDay;
}
public DateTime PeriodStart { get; set; }
public DateTime PeriodEnd { get; set; }
public IEnumerator<DateTime> GetEnumerator()
{
yield return PeriodStart;
yield return PeriodEnd;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
SingleDate
-class沒有改變(你不需要它,如果它不提供任何額外的功能):
public class SingleDate
{
public DateTime Date { get; set; }
}
什麼是'Dates'類型? –
@FelipeOriani排字錯誤 – mko
不要用「c」加前綴:[不要使用匈牙利符號](http://msdn.microsoft.com/en-us/library/ms229045(v = vs.110))。 aspx) – BCdotWEB