使用LINQ对当前对象和下一个对象进行一些计算

本文关键字:一个对象 计算 LINQ 对象 使用 | 更新日期: 2023-09-27 18:25:19

有没有一个优雅的解决方案可以遍历有序列表,对当前和下一个对象进行一些计算?LINQ必须有一种更聪明的方法来完成以下操作:

public static List<double> GetHoursBetweenDates(List<DateTime> aDates)
{
    List<double> lst = new List<double>();
    var olst = aDates.OrderByDescending(d => d).ToList();
    for (int i = 0; i < olst.Count - 1; i++)
    {
        lst.Add(olst[i].Subtract(olst[i+1]).TotalHours);
    }
    return lst;
}

使用LINQ对当前对象和下一个对象进行一些计算

比较列表中每个连续元素的最简单方法如下:

var sorted = aDates.OrderByDescending(d => d);
var results = 
    sorted.Zip(sorted.Skip(1), (a, b) => a.Subtract(b).TotalHours);

或者,您可以这样做:

var sorted = aDates.OrderByDescending(d => d).ToArray();
var results = 
    from i in Enumerable.Range(0, sorted.Length - 1)
    select sorted[i].Subtract(sorted[i + 1]).TotalHours;

但第二种方法只能使用List<T>T[]或任何支持数组式索引器的类型。

作为使用LINQ的Zip枚举器的解决方案的替代方案,该枚举器需要在列表上迭代两次,这里有一个自定义的LINQ运算符,它在序列上迭代并返回一对"移动的"元素:

static IEnumerable<Tuple<T, T>> Pairwise<T>(this IEnumerable<T> xs)
{
    using (IEnumerator<T> enumerator = xs.GetEnumerator())
    {
        if (!enumerator.MoveNext()) yield break;
        T current = enumerator.Current;
        while (enumerator.MoveNext())
        {
            T previous = current;
            current = enumerator.Current;
            yield return Tuple.Create(previous, current);
        }
    }
}

然后,您可以将其应用于DateTime序列,如下所示:

dates.Pairwise().Select(_ => _.Item2.Subtract(_.Item1).TotalHours);

其他选项是使用Aggregate函数,并将当前元素作为聚合返回。这还有一个额外的好处,即只迭代一次集合:

 public static List<double> GetHoursBetweenDates(List<DateTime> aDates)
 {
     List<double> lst = new List<double>();
     aDates.OrderByDescending(d => d).Aggregate((prev, curr) => { lst.Add(prev.Subtract(curr).TotalHours); return curr; });
     return lst;
 }

您可以使用moreLINQ库中的Incremental扩展方法:

public static List<double> GetHoursBetweenDates(List<DateTime> aDates)
{
    return aDates.OrderByDescending(d => d)
                 .Incremental((p,n) => p.Subtract(n).TotalHours)
                 .ToList();
}

它正是你所需要的:

/// <summary>
/// Computes an incremental value between every adjacent element in a sequence: {N,N+1}, {N+1,N+2}, ...
/// </summary>
/// <remarks>
/// The projection function is passed the previous and next element (in that order) and may use
/// either or both in computing the result.<
/// If the sequence has less than two items, the result is always an empty sequence.
/// The number of items in the resulting sequence is always one less than in the source sequence.
/// </remarks>