I have array
int[] arr = { -2, 0, 1, 2, 3, 4, 5, 8, 9, 11, 13, 15, 18, 22, 25, 28, 29, 30 };
I need to write function that shows it as string and if numbers are near, like 1,2,3,4,5 – I need to show them 1-5.
I wrote this function in repository
public string[] GetArray() { int[] arr = { -2, 0, 1, 2, 3, 4, 5, 8, 9, 11, 13, 15, 18, 22, 25, 28, 29, 30 }; int? lastValue = arr.FirstOrDefault(); var groupDataIntoAdjacentBlocks = arr.Segment(i => { var result = lastValue != null && (lastValue != (i - 1)); lastValue = i; return result; } ); var convertSetsIntoRanges = groupDataIntoAdjacentBlocks.Select(z => { var data = z.ToList(); if (data.Count() == 1) return data.First().ToString(); return data.First().ToString() + "-" + data.Last().ToString(); }); var finalresult = (string.Join(",", convertSetsIntoRanges)); return new[] { finalresult }; }
And call it like this in controller
public JsonResult GetArray() { var arrayresult = _arrayrepo.GetArray(); return Json(arrayresult, JsonRequestBehavior.AllowGet); }
Any suggestions how I can improve my code?