- 一定報告公告之日起一個數據對象,
- ,並在該日
即該類將如下所示:
class Report
{
DateTime announcementDate;
double ValueAnnounced;
}
因此,考慮具有以下值的報表列表S:
List<Report> reports = new List<Report>;
Report newReport = new Report();
newReport.announcementDate =Convert.ToDateTime("1/1/2011"); newReport.ValueAnnounced = 5;reports.Add(newReport);
newReport.announcementDate = Convert.ToDateTime("2/1/2011"); newReport.ValueAnnounced = 10;reports.Add(newReport);
newReport.announcementDate = Convert.ToDateTime("3/1/2011"); newReport.ValueAnnounced = 15;reports.Add(newReport);
現在,我需要的是,我需要建立一個新的列表「,將有每個日曆日期從2011/1/1至2011/3/31公佈的最新值。 「
即LINQ將返回其將具有以下元素的列表:
dailyReport[0].calendarDate = 1/1/2011; dailyReport[0].latestValue = 5;
dailyReport[1].calendarDate = 1/2/2011; dailyReport[2].latestValue = 5;
dailyReport[2].calendarDate = 1/3/2011; dailyReport[3].latestValue = 5;
...
...
...
dailyReport[30].calendarDate = 2/1/2011; dailyReport[30].latestValue = 10;
dailyReport[31].calendarDate = 2/2/2011; dailyReport[31]latestValue = 10;
dailyReport[32].calendarDate = 2/3/2011; dailyReport[32].latestValue = 10;
dailyReport[33].calendarDate = 2/4/2011; dailyReport[33].latestValue = 10;
...
...
...
dailyReport[60].calendarDate = 3/1/2011; dailyReport[60].latestValue = 15;
dailyReport[61].calendarDate = 3/2/2011; dailyReport[61].latestValue = 15;
dailyReport[62].calendarDate = 3/3/2011; dailyReport[62].latestValue = 15;
...
...
...
dailyReport[90].calendarDate = 3/31/2011; dailyReport[62].latestValue = 15;
我已經可以產生dailyReport清單,這個循環的幫助:
List<Report> dailyReport = new List<Report>;
foreach (DateTime calendarDay in EachDay(StartDate, EndDate))
{
var latestAvailableReport =
(
from theReport in reports
where theReport.announcementDate <= calendarDay
orderby theReport.announcementDate descending
select theReport
).ToList();
Report newDailyReport = new Report();
newDailyReport.announcementDate = latestAvailableReport[0].announcementDate;
newDailyReport.ValueAnnounced = latestAvailableReport[0].ValueAnnounced;
dailyReport.Add(newDailyReport);
}
和支持方法EachDay看起來像這樣:
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for(var day = from.Date; day.Date <= thru.Date; day =day.AddDays(1))
yield return day;
}
但是我的問題是,我可以感覺到應該有更快(或者更優雅)的方式來生成每日報告列表 - 基本上是「填入最新值」版本的原始列表。
我認爲,優雅的方式顯然是一個聰明的LINQ設計 - 我無法弄清楚鑑於我目前的知識和能力。
請你幫我寫LINQ好嗎?
感謝您的興趣和時間,非常感謝。
Aykut Saribiyik
LINQ不是魔術,首先轉換你的代碼,以便使用循環。然後想想如何將它轉換成Linq。 – EZI 2015-02-09 18:35:45
感謝您的評論EZI。您的評論以任何方式幫助任何人,但它是適當注意的。謝謝你的時間。 – 2015-02-09 18:51:02
Aykut Saribiyik,我不同意,當閱讀該評論時,人們會知道什麼/如何不問。 – EZI 2015-02-09 19:04:01