C# 简单的序列生成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1196840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:37:46  来源:igfitidea点击:

Simple Sequence Generation?

c#linqsequence

提问by abelenky

I'm looking for an ultra-easy way to generate a list of numbers, 1-200. (it can be a List, Array, Enumerable... I don't really care about the specific type)

我正在寻找一种非常简单的方法来生成数字列表,1-200。(可以是List、Array、Enumerable……具体的类型我不是很在意)

Apparently .Net 4.0 has a Sequence.Range(min,max)method. But I'm currently on .Net 3.5.

显然 .Net 4.0 有一个Sequence.Range(min,max)方法。但我目前在 .Net 3.5 上。

Here is a sample usage, of what I'm after, shown with Sequence.Range.

这是我所追求的示例用法,用 Sequence.Range 显示。

public void ShowOutput(Sequence.Range(1,200));

For the moment, I need consequitive numbers 1-200. In future iterations, I may need arbitrary lists of numbers, so I'm trying to keep the design flexible.

目前,我需要相应的数字 1-200。在未来的迭代中,我可能需要任意的数字列表,所以我试图保持设计的灵活性。

Perhaps there is a good LINQ solution? Any other ideas?

也许有一个很好的 LINQ 解决方案?还有其他想法吗?

采纳答案by Daniel Earwicker

.NET 3,5 has Rangetoo. It's actually Enumerable.Rangeand returns IEnumerable<int>.

.NET 3,5 也有Range。它实际上是Enumerable.Range并返回IEnumerable<int>

The page you linked to is very much out of date - it's talking about 3 as a "future version" and the Enumerablestatic class was called Sequenceat one point prior to release.

您链接到的页面已经过时了 - 它将 3 称为“未来版本”,并且在发布之前的某个时间点Enumerable调用了静态类Sequence

If you wanted to implement it yourself in C# 2 or later, it's easy - here's one:

如果您想在 C# 2 或更高版本中自己实现它,这很容易 - 这是一个:

IEnumerable<int> Range(int count)
{
    for (int n = 0; n < count; n++)
        yield return n;
}

You can easily write other methods that further filter lists:

您可以轻松编写其他方法来进一步过滤列表:

IEnumerable<int> Double(IEnumerable<int> source)
{
    foreach (int n in source)
        yield return n * 2;
}

But as you have 3.5, you can use the extension methods in System.Linq.Enumerableto do this:

但是因为你有 3.5,你可以使用扩展方法System.Linq.Enumerable来做到这一点:

var evens = Enumerable.Range(0, someLimit).Select(n => n * 2);

回答by JP Alioto

var r = Enumerable.Range( 1, 200 );

回答by dahlbyk

Check out System.Linq.Enumerable.Range.

查看System.Linq.Enumerable.Range

Regarding the second part of your question, what do you mean by "arbitrary lists"? If you can define a function from an intto the new values, you can use the result of Range with other LINQ methods:

关于您问题的第二部分,“任意列表”是什么意思?如果您可以定义一个从 anint到新值的函数,则可以将 Range 的结果与其他 LINQ 方法一起使用:

var squares = from i in Enumerable.Range(1, 200)
              select i * i;