Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert range of number in string to list of integer

I have a string "2-6,8,10-15,20-23"

I need to have it converted to a fully populated range of numbers in an array as below:

{2,3,4,5,6,8,10,11,12,13,14,15,20,21,22,23}

Do you have any ideas how to convert it?

like image 682
Ranhot Avatar asked Jan 17 '26 21:01

Ranhot


1 Answers

Mark Heath has a course on LINQ at PluralSight that addresses this very well. Using LINQ, you can quickly do this using the example shown below.

string value = "7-10,2,5,12,17-18";
var result = value.Split(',')
                  .Select(x => x.Split('-'))
                  .Select(p => new { First = int.Parse(p.First()), Last = int.Parse(p.Last()) })
                  .SelectMany(x => Enumerable.Range(x.First, x.Last - x.First + 1))
                  .OrderBy(z=>z);

The Split creates an array out of the string. The first Select creates an array of arrays that have 1 or 2 elements apiece. The second Select creates an anonymous type indicating the starting and ending value based on the array values. The SelectMany uses the Enumerable.Range method to create a range of numbers from each anonymous object, then flattens it into an IEnumerable collection of integers. Finally, the OrderBy puts the numbers in order for reporting and other use.

like image 128
Brian Payne Avatar answered Jan 19 '26 15:01

Brian Payne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!