LINQ通过某种规则将List<IEnumerable<T>>合并为一个IEnumerable<T>。

问题描述 投票:7回答:4

假设我有一个 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();
        }
    } 

但是,这看起来很 "小儿科"。有没有一种LINQ式的方法来实现这个功能?

c# linq
4个回答
8
投票

你可以在IEnumerables上聚合Zip方法。

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

这样做的目的是基本重复应用相同的Zip方法。对于四个IEnumerables,这将扩展到。

wfuncs[0].Zip(wfuncs[1], (d, dnext) => d + dnext)
         .Zip(wfuncs[2], (d, dnext) => d + dnext)
         .Zip(wfuncs[3], (d, dnext) => d + dnext);

试试吧 试试:


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();
        }
    }
}

利用这个,我设法压缩了我的组合生成器。

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);
    }
    // ...
}

3
投票

这种情况下,LINQ可能会更难理解,而且不会给你买到任何东西。你最好的赌注是直接修正你的示例方法。像这样的东西应该可以用。

public IEnumerable<double> Generator(IReadOnlyCollection<IEnumerable<double>> wfuncs)
{
    var enumerators = wfuncs.Select(wfunc => wfunc.GetEnumerator())
        .ToList();

    while(enumerators.All(e => e.MoveNext()))
    {
        yield return enumerators.Sum(s => s.Current);
    }
} 

0
投票

有一个非常简单的方法可以做到这一点.

public IEnumerable<double> Generator(List<IEnumerable<double>> wfuncs)
{
    return wfuncs.SelectMany(list => list);
}
© www.soinside.com 2019 - 2024. All rights reserved.