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


//potential input
//100 101

//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.


About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: