An enumeration giving an unexpected result

class Foo { public static IEnumerable<int> Range(int start, int end) { return Enumerable.Range(start, end); } public static void PrintRange(IEnumerable<int> r) { foreach (var item in r) { Console.Write(" {0} ", item); } Console.WriteLine(); } } class Program { static void TestFoo() { Foo.PrintRange(Foo.Range(10, 20)); } static void Main() { TestFoo(); } } 

Expected Result:

 10 11 12 13 14 15 16 17 18 19 20 

Actual output:

 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 

What is the problem with this code? What's happening?

+4
source share
3 answers

The second parameter, Enumerable.Range determines the number of integers to generate, not the last integer in the range.

If necessary, simply create your own method or update the existing Foo.Range method to create a range from the start and end parameters.

+10
source

The second Range parameter is the number of items to create.

+4
source

Why is this not the end, but the bill?

How do you list an empty range if you have a start and end point? For example, suppose you have a text buffer on the screen and a selection, and the selection has one character, starting with character 12 and ending with character 12. How do you list this range? You list one character starting with character 12.

Now suppose the choices are ZERO characters. How do you list this? If you have a start, size, you just pass zero for size. If you have a beginning, an end, what are you doing? You cannot go 12 and 12.

Now you can say: "well, just don’t list it if its range is empty." Thus, you get a code that should look like this:

 var results = from index in Range(selectionStart, selectionSize) where blah blah blah select blah; 

and instead I write

 IEnumerable<Chicken> results = null; if (selectionSize == 0) { results = Enumerable.Empty<Chicken>(); } else { results = from index in Range(selectionStart, selectionEnd) where blah blah blah select blah; } 

which hurts my eyes.

+3
source

Source: https://habr.com/ru/post/1304459/


All Articles