Split an array into small arrays

I am sending an email to a list of people. I have a list of recipients in an array, but the list can be up to 500 people. Limiting the number of recipients sent by my mail server immediately (50 recipients)

therefore, if the list is> 50, I need to split it into different letters.

What is the best way to take one array and split it into arrays 50

eg:

If the array is 120 in length, I expect 3 arrays to be returned, one with 50, another with 50, and a third with 20.

+3
source share
6 answers

You can use the operation Batch of MoreLINQ :

Person[] array = ...;

var arrays = list.Batch(50).Select(x = x.ToArray());

foreach (Person[] shorterArray in arrays)
{
    ...
}

( IEnumerable<Person> , , Select).

+8

, , , , .

+3

, ArraySegment<T> ? , .

int recipient = 0;
while (recipient < recipients.Count) {
  ArraySegment<string> recipientSegment = new ArraySegment<string>(recipients, recipient, Math.Min(50, recipients.Count-recipient));
  // build your message here, using the recipientSegment for the names
  recipient += 50;
}
+3

LINQ, : Linq:

+1

Skip Take, LINQ. , LINQ , .. .

, , , , (.. ), , , , .

Here is an example of what this implementation might look like:

List<EmailAddress> list = new List<EmailAddress>();
const int BATCH_SIZE = 50;

for (int i = 0; i < list.Count; i += BATCH_SIZE)
{
   IEnumerable<EmailAddress> currentBatch = 
      list.Skip(i).Take(BATCH_SIZE);

   // do stuff...
}
0
source

Should LINQ be suitable for this?

0
source

Source: https://habr.com/ru/post/1716687/


All Articles