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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: