Sunday, 31 March 2013

Stringed Numbers

Doing computation over numbers stored as strings can be challenging. Finding the sum or max among all numbers stored as strings would be easy, but sorting the “string” numbers without type-casting them to integer/double is tricky.

Here, we’ll see how Anonymous methods come to the rescue for sum & max operations and Sort & OrderBy functionality for sorting “string” numbers.

Initially, we create a simple list of strings holding numbers in an arbitrary range. Let’s consider sorting. The strings “6” and “10” will be ordered as “10” -> “6” because the first character in “10” (i.e. ‘1’) has a lower ASCII value when compared to the first character of “6” (i.e. ‘6’ itself). But our desired Ascending-order sorting is “6” -> “10”. The culmination of Sort and OrderBy come in handy to resolve this issue.

Next, with the help of Anonymous functions, we convert every “string” number into Int32-type and figure out the sum & max separately.

In the end, there’s a small example worked out demonstrating the Ascending-Order Sort by using 2 strung-up OrderBy clauses rather than using the combination of Sort & OrderBy functionality.

Please check out the 2 video links where I go through this topic in more detail.

C# Experiments: Stringed Numbers (Part 1)

The code typed-in during the tutorial session is as follows:-

            var stringedNumbers = new List<string>();

            //for (int i = 0; i < 3000; i++)
            for (int i = 3000; i > 0; i--)

            stringedNumbers = stringedNumbers.OrderBy(n => n.Length).ToList();

            int sumans = stringedNumbers.Sum(n => Convert.ToInt32(n));

            int max = stringedNumbers.Max(n => Convert.ToInt32(n));

            string s1 = "Hello-1000";
            string s2 = "Welcome-200";
            string s3 = "Morning-250 ";
            string s4 = "Afternoon-230";

            string output = String.Join("/", new List<string> { s1, s2, s3, s4 }.OrderBy(x =>  x.Substring(x.IndexOf('-'))).OrderBy(x => x.Substring(x.IndexOf('-')).Length));


Thank you for reading this post and watching the videos. Please Subscribe, Comment and Rate the channel if you liked the videos.

Goto C# Experiments to access more of such content! Thanks again!