我正在學習LINQ,並希望獲得與下面代碼等效的LINQ查詢。C#LINQ TimeSpan平均天數
IEnumerable列表包含一個排序的日期列表:從最舊到最新。
以下代碼通過從數組的第一個元素日期減去數組的第零個元素日期,從第二個元素日期減去第二個元素日期,從第三個元素減去第二個元素日期等等,得出TimeSpan
s。然後在代碼中的其他地方對TimeSpan.Days
進行平均。我相信LINQ查詢不需要構建數組。 IEnumerable<DateTime>
結構可以用作數據源。
IEnumerable<DateTime> list; // contains a sorted list of oldest to newest dates
// build DateTime array
DateTime[] datesArray = null;
TimeSpan ts;
List<int> daysList = new List<int>();
datesArray = (from dt in list
select dt).ToArray();
// loop through the array and derive the TimeSpan by subtracting the previous date,
// contained in the previous array element, from the date in the current array element.
// start the loop at element 1.
for (int i = 1; i < list.Count(); i++)
{
ts = datesArray[i].Subtract(datesArray[i - 1]); // ts is a TimeSpan type
daysList.Add(ts.Days);
// add the TimeSpan.Days to a List<int> for averaging elsewhere.
}
謝謝
斯科特
`(DT從列表中選擇DT).ToArray()`是更好的寫作`list.ToArray()`` – Gabe 2011-02-12 01:47:58