Being able to group data into batches can be quite useful and often done for reporting purposes, but I found it handy to group a series of multiple choice questions and answers for displaying a given tester. In this case, it was for a quiz that asked the capital of a given state with four possible answers provided for each question (see Figure 2). The data was in a SQL Server database table, but it could have been retrieved via a service or a text file.
Since the data was in a table I looked at using NTILE, but TSQL it didn’t provide me with all the functionality I needed and LINQ didn’t provide the appropriate extension method either. So rather that creating my own extension method, I leveraged MoreLINQ and its Batch method. MoreLINQ is a great open source library that extends LINQ and is available as a NuGet package as well.
As a simple example, to group a collection of numbers into batches of 4, you would write a query like this:
The above query would group the integers into three batches, two of which would contain 4 values and the last one containing 2 values as shown in Figure 1.
Figure 1. Integer collection in batches of 3
Now in the case of the questions/quiz, each question was comprised of 7 rows.
Figure 2. Sample Quiz Data
The question number, the correct answer, the question and the four multiple choice answers to choose from. The query to processed the data is listed below.
.Batch(7, q => q.Select(x => x.Value).ToArray())
.Select(b => new
Id = b,
Answer = b,
Question = b,
Choice1 = b,
Choice2 = b,
Choice3 = b,
Choice4 = b
It groups the data from the CapitalQuiz table into batches of 7 rows, then uses the second overload of the Batch extension method to specify a result selector that retrieves only the Value column from the table. The values are then converted to an array so that the individual elements could then be easily selected for further processing and the results are shown below.
As you can see, using MoreLINQ Batch method makes it quite easy to group data into batches; it’s intuitive and reduces the amount of code you’d have to write. There are many uses for batching data as shown above, processing sales by week or month, optimizing the import or export of data, etc. Be sure to check out the MoreLINQ library, if you’re not familiar with it as it provides dozens of useful methods that extend LINQ to Objects.
About the Author:
TopLine Strategies delivers the complete integration and development of sales, marketing and customer service technologies that enable corporate clientele to improve revenue streams and strengthen customer interactions. Our project management and consulting is designed to achieve timely delivery, 100 percent user adoption of the technologies we implement and deliver measurable returns on investments for our clients.