How do i add to a List<int> also the numbers in between?

Refresh

March 2019

Views

105 time

1

This is the code:

_fts = new List<int>();
                    for (int i = 0; i < LR.Count; i++)
                    {
                        _fts.Add(LR[i].start);
                        _fts.Add(LR[i].end);
                    }

In the end _fts have for example 15 numbers for example the first 4 indexs:

[0] 88
[1] 96
[2] 93
[3] 100

I need before im doing the adding: _fts.Add I need to calculate somehow each two couple start and end and get the numbers between and add all this numbers to the _fts.

For example end is 96 and start 88 so I need to add to the _fts the numbers:

88 89 90 91 92 93 94 95 96

Then end is 100 and start is 93 so again add to _fts the numbers:

93 94 95 96 97 98 99 100

So now _fts will looks like:

88 89 90 91 92 93 94 95 96 93 94 95 96 97 98 99 100

If the number for example 93 and 94 appears twice it's ok I need it this way since after it I parse the List and put it in directories ...Never mind this part with the directories.

What I need to add the numbers in between each couple. And not only to add 88 and 96 or 93 and 100.

How can I do it ?

3 answers

0

Use Enumerable.Range for each range. It takes the starting number and count, so you'll need to calculate count.

        var LR = new []
                     {
                         new {start = 88, end = 96},
                         new {start = 93, end = 100}
                     };

        var _fts = new List<int>();
        for (int i = 0; i < LR.Length; i++)
        {
            _fts.AddRange(Enumerable.Range(LR[i].start, LR[i].end - LR[i].start + 1));
        }

        Console.WriteLine(String.Join(" ", _fts));
0

Assuming that LR is an enumerable collection, you could simplify this to:

var _fts = LR.SelectMany( lr => Enumerable.Range(lr.start, lr.end-lr.start+1) );

If you want to eliminate duplicates, add .Distinct() to the statement.

2

Like this?

for (int j = LR[i].start; j <= LR[i].end; j++)
{
    _fts.Add(j);
}