Pivoting a collection of arrays

╄→尐↘猪︶ㄣ 提交于 2019-12-06 14:34:42

I would, personally, force the evaluation of your collection in advance, and use it as an array. Right now, each time you call ElementAt, you're going to evaluate the IEnumerable<T> again, causing a lot of repeated searching.

By forcing it to evaluate to an array in advance, you simplify the entire process. Something like:

public static IEnumerable<IValueCollection> PivotValues(this MeasurementCollection items)
{
    if(items.IsQuantized())
    {
        int elementLength = (int)items.First().Template.Frequency;
        var itemArray = items.ToArray();
        for (int n = 0; n < itemArray.Length; n++)
        {
            IValueCollection v = new MeasurementValueCollection(elementLength);
            for (int m = 0; m < elementLength; m++)
            {
                v[m] = itemArray[m].Values[n];
            }
            yield return v;
        }
    }
    else
        yield break; // Handle the case where IsQuantized() returns false...
}

If you control MeasurementValueCollection, I would add a constructor which takes an IEnumerable<decimal> as input, as well. You could then do:

public static IEnumerable<IValueCollection> PivotValues(this MeasurementCollection items)
{
    if(items.IsQuantized())
    {
        var elements = Enumerable.Range(0, (int)items.First().Template.Frequency);
        var itemArray = items.ToArray();

        foreach(var element in elements)
            yield return new MeasurementValueCollection(
                                 itemArray.Select( 
                                   (item,index) => itemArray[index].Value[element]
                                 )
                             );
    }
    else
        yield break; // Handle the case where IsQuantized() returns false...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!