Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting wrong range of numbers

Given the pair of 2 strings "2-4,6-8" I want to separate these 2 pairs and find all numbers between those range.
So first pair 2-4 should return me 2, 3, 4
Second pair 6-8 should return 6, 7, 8

I tried below code

 var splittedString = ln.Split(",");
 var firstPair = splittedString[0];
 var secondPair = splittedString[1];
 var splittedFirstPair = firstPair.Split("-");

 IEnumerable<int> firsPairRange = Enumerable.Range(
   Convert.ToInt32(splittedFirstPair[0]), 
   Convert.ToInt32(splittedFirstPair[1]));

 var splittedSecondPair = secondPair.Split("-");

 IEnumerable<int> secondPairRange = Enumerable.Range(
   Convert.ToInt32(splittedSecondPair[0]), 
   Convert.ToInt32(splittedSecondPair[1]));

But the variable firsPairRange gives me output 2,3,4,5 and the variable secondPairRange gives me output 6,7,8,9,10,11,12,13

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t understand why and how to fix it?

>Solution :

string ln = "2-4,6-8";
var splittedString = ln.Split(',').Select(x => x.Split('-').Select(int.Parse).ToArray());
int[] first = splittedString.ElementAt(0);
int[] second = splittedString.ElementAt(1);
var firstPairRange = Enumerable.Range(first[0], first[1] - first[0] + 1);
var secondPairRange = Enumerable.Range(second[0], second[1] - second[0] + 1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading