【发布时间】:2011-02-12 01:09:41
【问题描述】:
我正在学习 LINQ,并且想要一个与以下代码等效的 LINQ 查询。
IEnumerable 列表包含一个排序的日期列表:从最旧到最新。
下面的代码通过从数组的第一个元素日期中减去数组的第零个元素日期,从第 2 个元素中减去第一个元素日期,从第 3 个元素中减去第 2 个元素,得出 TimeSpans。 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.
}
谢谢,
斯科特
【问题讨论】:
-
(from dt in list select dt).ToArray()最好写成list.ToArray()