LINQ通过某种规则将<IEnumerable <T >>列入一个IEnumerable <T>

mmi*_*mix 7 c# linq

假设我有一个List<IEnumerable<double>>包含可变数量的无限双数源.让我们说它们都是波发生器功能,我需要将它们叠加到单个波形发生器中,IEnumerable<double>简单地通过从每个波形中取出下一个数字并将它们相加.

我知道我可以通过迭代器方法做到这一点,如下所示:

    public IEnumerable<double> Generator(List<IEnumerable<double>> wfuncs)
    {
        var funcs = from wfunc in wfuncs
                    select wfunc.GetEnumerator();

        while(true)
        {
            yield return funcs.Sum(s => s.Current);
            foreach (var i in funcs) i.MoveNext();
        }
    } 
Run Code Online (Sandbox Code Playgroud)

然而,它似乎相当"行人".是否有LINQ-ish方法来实现这一目标?

fri*_*ich 8

您可以在IEnumerables上聚合Zip方法.

    public IEnumerable<double> Generator(List<IEnumerable<double>> wfuncs)
    {
        return wfuncs.Aggregate((func, next) => func.Zip(next, (d, dnext) => d + dnext));
    }
Run Code Online (Sandbox Code Playgroud)

这样做基本上一遍又一遍地应用相同的Zip方法.有了四个IEnumebles,这将扩展到:

wfuncs[0].Zip(wfuncs[1], (d, dnext) => d + dnext)
         .Zip(wfuncs[2], (d, dnext) => d + dnext)
         .Zip(wfuncs[3], (d, dnext) => d + dnext);
Run Code Online (Sandbox Code Playgroud)

尝试一下:小提琴


mmi*_*mix 4

我想如果不扩展 LINQ 就没有办法解决这个问题。这就是我最后写的内容。我将尝试联系 MoreLinq 作者以某种方式将其包含在内,它在某些旋转场景中可能很有用:

public static class EvenMoreLinq
{
    /// <summary>
    /// Combines mulitiple sequences of elements into a single sequence, 
    /// by first pivoting all n-th elements across sequences 
    /// into a new sequence then applying resultSelector to collapse it
    /// into a single value and then collecting all those 
    /// results into a final sequence. 
    /// NOTE: The length of the resulting sequence is the length of the
    ///       shortest source sequence.
    /// Example (with sum result selector):
    ///  S1   S2   S2    |  ResultSeq
    ///   1    2    3    |          6 
    ///   5    6    7    |         18
    ///  10   20   30    |         60
    ///   6    -    7    |          -
    ///   -         -    |          
    /// </summary>
    /// <typeparam name="TSource">Source type</typeparam>
    /// <typeparam name="TResult">Result type</typeparam>
    /// <param name="source">A sequence of sequences to be multi-ziped</param>
    /// <param name="resultSelector">function to compress a projected n-th column across sequences into a single result value</param>
    /// <returns>A sequence of results returned by resultSelector</returns>
    public static IEnumerable<TResult> MultiZip<TSource, TResult>
                                  this IEnumerable<IEnumerable<TSource>> source, 
                                  Func<IEnumerable<TSource>, TResult> resultSelector)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (source.Any(s => s == null)) throw new ArgumentNullException("source", "One or more source elements are null");
        if (resultSelector == null) throw new ArgumentNullException("resultSelector");

        var iterators = source.Select(s => s.GetEnumerator()).ToArray();
        try
        {
            while (iterators.All(e => e.MoveNext()))
                yield return resultSelector(iterators.Select(e => e.Current));
        }
        finally
        {
            foreach (var i in iterators) i.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它我成功地压缩了我的组合生成器:

interface IWaveGenerator
{
    IEnumerable<double> Generator(double timeSlice, double normalizationFactor = 1.0d);
}


[Export(typeof(IWaveGenerator))]
class CombinedWaveGenerator : IWaveGenerator
{
    private List<IWaveGenerator> constituentWaves;

    public IEnumerable<double> Generator(double timeSlice, double normalizationFactor = 1)
    {
        return constituentWaves.Select(wg => wg.Generator(timeSlice))
                               .MultiZip(t => t.Sum() * normalizationFactor);
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • `iterators` 永远不可能是 `null`,所以对它进行 null 检查是没有意义的。 (2认同)