简体   繁体   English

在C#中编写[0..100]的最佳方法是什么?

[英]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 . 这已经在框架中: Enumerable.Range

For other types, you might be interested in the range classes in my MiscUtil library. 对于其他类型,您可能对我的MiscUtil库中的范围类感兴趣。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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