db28
db28

Reputation: 33

Change loops on 2D List to LINQ

I am relatively new to C# and newer to LINQ. I haven't found a good way to do this using LINQ (meaning an example on here that does almost exactly this, lol), but it seems like there should be a way to eliminate one of my loops.

I have a 2D List of List. I want to make a 2D List of averaged chunks of data of each of the sub Lists.

Example input:

averageSize = 2

input List = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}

expected output List:

{{1.5,3.5}, {5.5,7.5}, {9.5, 11.5}}

I have working code with a foreach loop and a for loop. waveData is the input 2D list, averageSize is the number of values to average together

            int tempIndex = 0;
        List<List<double>> averages = new List<List<double>>();
        foreach (List<double> phaseData in waveData)
        {
            averages.Add(new List<double> { });
            for (int i = 0; i <= (phaseData.Count-averageSize); i+= averageSize)
            {
                averages[tempIndex].Add(phaseData.GetRange(i, averageSize).Average());
            }
            tempIndex++;
        }

Upvotes: 3

Views: 70

Answers (1)

Andrew Kulikov
Andrew Kulikov

Reputation: 61

Batch extension method from MoreLINQ package is exactly what you need. It takes the source enumerable and divides it into batches of given size. Resulting LINQ expression will look like this:

public List<List<double>> CalculateBatchAverages(List<List<double>> data, int batchSize = 2)
{
    return data.Select(list => list
            .Batch(batchSize)
            .Select(batch => batch.Average())
            .ToList())
        .ToList();
}

Upvotes: 1

Related Questions