December 3, 2010

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



Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Split a String Collection into Groups using LINQ"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions