0

I have a comma delimited string that I need to break into array ranges that can be passed into SQL server's BETWEEN statement.

For instance, say I have the following string below, I need the corresponding returnVal returned;

string delimited = "1,2,5,6,7,8,11,12,13,15,16,17,18,19"; 
returnVal = int[,] ranges = new int[4, 2] { { 1, 2 }, { 5, 8 }, { 11, 13 }, { 15, 19 } };

My SQL Between Statement would then look like

WHERE (ID BETWEEN 1 AND 2) OR (ID BETWEEN 5 AND 8)  OR (ID BETWEEN 11 AND 13)  OR (ID BETWEEN 15 AND 19) 

Rather than

WHERE ID IN(1,2,5,6,7,8,11,12,13,15,16,17,18,19)

My actual delimited string is over 5000 IDs so I need to use BETWEEN statements rather than IN statements for efficiency.

What would be the most efficient way to do this using C#?

6
  • What is the logic for the ranges? there are 14 number but you only use 8 Jun 15, 2019 at 1:20
  • I saw the question and dont see anything suggesting the logic behind Jun 15, 2019 at 1:23
  • You are probably asking the wrong question What is the XY problem? If you have 5000 id create a temporal table with index and do a join. Jun 15, 2019 at 1:39
  • A given ID value cannot be "between 1 and 2" AND "between 5 and 8". So your <would look like> version is logically incorrect. If you desire to use ranges, you need to use OR, not AND. Agree with Juan - Erland discusses the use of a TVP here
    – SMor
    Jun 15, 2019 at 12:18
  • Good point, I have modified my question according to your comment.
    – TroySteven
    Jun 15, 2019 at 21:35

1 Answer 1

2

The following will solve your problem:

If your ints are a delimited string you can use split to convert it into an int array.

var intArray = **array of integers**
var ranges = new List<List<int>>();

int? topRange = intArray[0];
int? lastId = null;
int bottomRange; 
foreach(int id in intArray)
{
    if(topRange == null)
    {
        topRange = id;
    }
    if (lastId != null && id != (lastId + 1))
    {
        bottomRange = lastId.Value;
        ranges.Add(new List<int>() { topRange.Value, bottomRange });
        topRange = id;
    }
    lastId = id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.