Menus

Tuesday, December 4, 2012

Split a String Collection into Groups using LINQ

I was recently working on an interesting problem which involved splitting a string collection into groups. We had a huge collection of email addresses stored in a string array. The task was to loop the array and select 10 emails at a time and send it for processing.
Here’s some LINQ code originally shared by Eric Lippert, that can be helpful if you have a similar requirement without using a loop for grouping.
static void Main(string[] args)
{
    string[] email = {"One@devcurry.com", "Two@devcurry.com",
                        "Three@devcurry.com", "Four@devcurry.com",
                        "Five@devcurry.com", "Six@devcurry.com",
                        "Seven@devcurry.com", "Eight@devcurry.com"};

    var emailGrp = from i in Enumerable.Range(0, email.Length)
                                    group email[i] by i / 3;

    foreach(var mail in emailGrp)
        SendEmail(string.Join(";", mail.ToArray()));
                                         

    Console.ReadLine();
}

     
static void SendEmail(string email)
{
    // Assuming that you have code for sending mails here
    Console.WriteLine(email);
    Console.WriteLine("--Batch Processed--");
}
The code above uses the LINQ GroupBy operator to group 3 email addresses at a time and send it for processing. Note that a group...by clause translates to an invocation of GroupBy.
OUTPUT
Split String Collection

No comments:

Post a Comment