C#: Cleanest way to divide a string array into N instances N items long

后端 未结 8 1373
我寻月下人不归
我寻月下人不归 2020-12-23 10:40

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

8条回答
  •  不思量自难忘°
    2020-12-23 11:16

    Seems similar to this question: Split a collection into n parts with LINQ?

    A modified version of Hasan Khan's answer there should do the trick:

    public static IEnumerable> Chunk(
        this IEnumerable list, int chunkSize)
    {
        int i = 0;
        var chunks = from name in list
                     group name by i++ / chunkSize into part
                     select part.AsEnumerable();
        return chunks;
    }
    

    Usage example:

    var addresses = new[] { "a@example.com", "b@example.org", ...... };
    
    foreach (var chunk in Chunk(addresses, 50))
    {
        SendEmail(chunk.ToArray(), "Buy V14gr4");
    }
    

提交回复
热议问题