c# .net split strings with math divrem using lambda linq

Recently I came across a nice alternative to loops using linq for evenly splitting a string using Math.DivRem.

The following example illustrates how this can be used to parse a sequence of numbers based on a time series which may give variable results in a custom messaging protocol.

(inspired by R. Prestol)

//not the complete classes but satisfies the below example
class message {
string series {get;set;}
}

  string[] series = message.series.Split(' '); //will NOT throw an exception if series string is empty
            int Rem = 0;
            int d = Math.DivRem(name.Length, 2, out Rem); //hardcoded two for simplicity in this example
 
//valueB will contain the same value as valueA if there is no second value in the sequence
            string valueA = string.Join(" ", sentence.Take(Math.Max(d, 1)).ToArray());
            string valueB = string.Join(" ", sentence.Skip(d).Take(d + Rem).ToArray());

int average = (Convert.ToInt32(valueA) + Convert.ToInt32(valueB)) / 2; //2 would also need to be dynamic here

Console.WriteLine(average.ToString());

//potential input
//100 101
//100

//output for average
//first input: 100
//second input: 100

A significant figure is lost (.5) on first input since valueA and valueB are converted to int. Conversion to decimal, double etc would of course maintain this detail depending on the rounding you are looking for.

Advertisements

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on March 15, 2013, in Uncategorized and tagged , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: