我正在学习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