使用 LINQ 和 C# 的随机数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/254844/
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
Random array using LINQ and C#
提问by Ryan
I was reading an article on MSDN Magazine about using the Enumerable class in LINQto generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:
我正在阅读 MSDN 杂志上关于使用LINQ 中的Enumerable 类生成随机数组的文章。这篇文章使用了 VB.NET,我不能立即确定 C# 中的等价物是什么:
Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
采纳答案by HanClinto
The Developer Fusion VB.Net to C# convertersays that the equivalent C# code is:
该开发者融合VB.Net到C#转换器说,相当于C#代码为:
System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
For future reference, they also have a C# to VB.Net converter. There are several other toolsavailable for this as well.
为了将来参考,他们还有一个C# 到 VB.Net 转换器。还有其他几种工具可用于此目的。
回答by James Curran
Random rnd = new Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
回答by Adam Alexander
Best I can do off the top of my head without access to Visual Studio (crosses fingers):
最好的我可以在没有访问 Visual Studio 的情况下完成我的头顶(交叉手指):
System.Random rnd = New System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);
回答by Daniel Plaisted
I initially thought this would be a bad idea since the sort algorithm will need to do multiple comparisons for the numbers, and it will get a different sorting key for the same number each time it calls the lambda for that number. However, it looks like it only calls it once for each element in the list, and stores that value for later use. This code demonstrates this:
我最初认为这是一个坏主意,因为排序算法需要对数字进行多次比较,并且每次调用该数字的 lambda 时,它都会为同一数字获得不同的排序键。但是,它看起来只为列表中的每个元素调用一次,并存储该值以供以后使用。此代码演示了这一点:
int timesCalled = 0;
Random rnd = new Random();
List<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>
{
timesCalled++;
return rnd.Next();
}
).ToList();
Assert.AreEqual(timesCalled, 100);
回答by Marcus Griep
Using the C5 Generic Collection Library, you could just use the builtin Shuffle()
method:
使用C5 Generic Collection Library,您可以只使用内置Shuffle()
方法:
IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));
numbers.Shuffle();
回答by FouZ
What about something far more easy...
更简单的事情呢...
Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())