Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Range.AsEnumerable() extension #762

Closed
MisinformedDNA opened this issue Sep 28, 2020 · 2 comments
Closed

Add Range.AsEnumerable() extension #762

MisinformedDNA opened this issue Sep 28, 2020 · 2 comments

Comments

@MisinformedDNA
Copy link

Currently, we can create a sequence using a static method:

MoreEnumerable.Sequence(start, stop);

However, it would be nice if we could instead start with a C# construct like:

(start..stop).AsEnumerable();

I propose adding:

public static IEnumberable<int> AsEnumerable(this Range range);
@atifaziz
Copy link
Member

This would belong in a more general library of extension methods or even one specific for Range. Unfortunately, it's out of scope for this library since MoreLINQ doesn't provide extension methods for other types than sequences (IEnumerable<>). It would also cause some confusion with MoreEnumerable.Sequence since, unlike Range, its stop argument is inclusive. It could also lead to subtle bugs if, for example, (starting with C# 9) some provided an iteration extension for Range so it could be used in foreach loops like so:

foreach (var x in 1..10)
    Console.WriteLine(x);

static class RangeExtensions
{
    public static IEnumerator<int> GetEnumerator(this Range range)
    {
        var max = (long)int.MaxValue + 1;
        long Normalize(Index i) => i.IsFromEnd ? max - i.Value : i.Value;
        var (start, end) = (Normalize(range.Start), Normalize(range.End));
        for (var i = start; i < end; i++)
            yield return checked((int)i);
    }
}

The above will print numbers from 1 to 9. It won't be simply interchangeable with MoreEnumerable.Sequence or an AsEnumerable extension method for Range that includes the end.

Putting all that aside, Range isn't really designed to be used for representing a range of numbers but rather a slice defined by indicies. Both its Start and End are typed as Index so using it otherwise would just mislead or bring about artificial limitations. For example, you can't really use it to do something like MoreEnumerable.Sequence(-10, 10) since Index cannot be initialized with a negative number.

@atifaziz
Copy link
Member

You might be interested in checking out #748 where a more appropriate use of Range as a one-stop shortcut to many extensions (or combinations thereof) is being proposed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants