C#: Cleanest way to divide a string array into N instances N items long
arrays, c#, loops, string
Solution
You want elegant and succinct, I'll give you elegant and succinct:
var fifties = from index in Enumerable.Range(0, addresses.Length)
group addresses[index] by index/50;
foreach(var fifty in fifties)
Send(string.Join(";", fifty.ToArray());
Why mess around with all that awful looping code when you don't have to? You want to group things by fifties, then group them by fifties. That's what the group operator is for!
UPDATE: commenter MoreCoffee asks how this works. Let's suppose we wanted to group by threes, because that's easier to type.
var threes = from index in Enumerable.Range(0, addresses.Length)
group addresses[index] by index/3;
Let's suppose that there are nine addresses, indexed zero through eight
What does this query mean?
The `Enumerable.Range` is a range of nine numbers starting at zero, so `0, 1, 2, 3, 4, 5, 6, 7, 8`.
Range variable `index` takes on each of these values in turn.
We then go over each corresponding `addresses[index]` and assign it to a group.
What group do we assign it to? To group `index/3`. Integer arithmetic rounds towards zero in C#, so indexes 0, 1 and 2 become 0 when divided by 3. Indexes 3, 4, 5 become 1 when divided by 3. Indexes 6, 7, 8 become 2.
So we assign `addresses[0]`, `addresses[1]` and `addresses[2]` to group 0, `addresses[3]`, `addresses[4]` and `addresses[5]` to group 1, and so on.
The result of the query is a sequence of three groups, and each group is a sequence of three items.
Does that make sense?
Remember also that the result of the query expression is a query which represents this operation. It does not perform the operation until the `foreach` loop executes.
Problem
I know how to do this in an ugly way, but am wondering if there is a more elegant and succinct method. I have a string array of e-mail addresses. Assume the string array is of arbitrary length -- it could have a few items or it could have a great many items. I want to build another string consisting of say, 50 email addresses from the string array, until the end of the array, and invoke a send operation after each 50, using the string of 50 addresses in the Send() method. The question more generally is what's the cleanest/clearest way to do this kind of thing. I have a solution that's a legacy of my VBScript learnings, but I'm betting there's a better way in C#.