简体   繁体   中英

What's the best way to write [0..100] in C#?

I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.

Here's an example:

IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
    for (int i = from; i <= to; i++)
    {
        yield return i;
    }
}

This is already in the framework: Enumerable.Range .

For other types, you might be interested in the range classes in my MiscUtil library.

Alternately, a fluent interface from extension methods:

public static IEnumerable<int> To(this int start, int end)
{
    return start.To(end, i => i + 1);
}

public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
    int current = start;
    while (current < end)
    {
        yield return current;
        current = next(current);
    }
}

used like:

1.To(100)

Here's an idea that lets a range class work with both things that are discrete and those which are not:

class Range<T> where T: IComparable<T>
{
    public T From { get; set; }
    public T To { get; set; }

    public Range(T from, T to) { this.From = from; this.To = to; }

    public IEnumerable<T> Enumerate(Func<T, T> next)
    {
        for (T t = this.From; t.CompareTo(this.To) < 0; t = next(t))
        {
            yield return t;
        }
    }

    static void Example()
    {
        new Range<int> (0, 100).Enumerate(i => i+1)
    }
}

And if you think that supplying the enumerator each time is annoying, here's a derived class:

class EnumerableRange<T> : Range<T>, IEnumerable<T>
    where T : IComparable<T>
{
    readonly Func<T, T> _next;
    public EnumerableRange(T from, T to, Func<T, T> next)
        : base(from, to)
    {
        this._next = next;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return Enumerate(this._next).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM