Question: I am looking to extract ranges from an list of integers using linq:

for example I am looking to split the following list: 

```
List<int> numberList = new List<int>() { 30, 60, 90, 120, 150, 180, 270, 300, 330 };  

```

into a list of integer ranges that will look like:

```
{ 30, 180 }
{ 270, 330 }

```

ie: where the next seq is greater than 30

another example : 

```
List<int> numberList = new List<int>() { 30, 60, 120, 150, 270, 300, 330 };  

```

into a list of integer ranges that will look like:

```
{ 30, 60 }
{ 120, 150 }
{ 270, 330 }

```

I have tried with for loops to find the best way possible however I don't
know where to start trying to use a linq query to do this.

Answer: 
You could write a method to handle the split:

```
IEnumerable<IList<int>> SplitValues(IList<int> input, int difference = 30)
{
    List<int> results = new List<int>();
    int last = input.First();
    foreach(var value in input)
    {
        if (value - last > difference)
        {
            yield return new[] {results.First(), results.Last()};
            results = new List<int>();
        }

        results.Add(value);
        last = value;
    }

    yield return new[] {results.First(), results.Last()};
}

```

This matches your specifications as described, returning:

```
{ 30, 60 }
{ 120, 150 }
{ 270, 330 }

```

Note that a single value within the collection without a range will be duplicated. For example, `{ 30, 120, 150 }` will return:

```
{ 30, 30 }
{ 120, 150 }

```
You can use `TakeWhile` and add the result to another list

```
void SplitByRange()
{
    List<int> numberList = new List<int>() { 30, 60, 120, 150, 270, 300, 330 }; 
    IEnumerable<int> aux = new List<int>();

    int n = numberList.First();
    int skip = 0;
    List<List<int>> output = new List<List<int>>();

    while ((aux = numberList.Skip(skip).TakeWhile(o => { bool r = (o - n) <= 30; n = o; return r; })).Count() > 0)
    {
        output.Add(aux.ToList());
        skip += aux.Count();
    }
}

```

At the end `numberList` will be empty and `output` will be a list of lists.

```
output[0]  // { 30, 60 }
...

```

The current code will required at least 1 element on the list, and if you have

```
{ 30, 100 }

```

It will return as two lists with 1 element in each

```
{ 30 }
{ 100 }

```