[英]output whole list in C#
in python language i can easily do this and output is whole list:在 python 语言中,我可以轻松做到这一点,output 是整个列表:
import random
list = [random.randrange(150) for i in range(10)]
print(list)
Can i do this thing in C# language without for cycle like this?我可以用 C# 语言做这件事而不用这样的循环吗? Because output seperates my list's elements.
因为 output 分隔了我列表的元素。
List<int> list = new List<int> ();
Random rnd = new Random();
for (int i = 0; i < 10; i++){
list.Add(rnd.Next (150));
}
for(int i = 0; i < list.Count; i++){
Console.WriteLine(list[i]);
}
Well, we can do it in one line if you want as well.好吧,如果您愿意,我们也可以在一行中完成。 This code is also thread-safe but requires .NET 6.0 or higher due to the use of
Random.Shared
.此代码也是线程安全的,但由于使用了
Random.Shared
,因此需要 .NET 6.0 或更高版本。
Console.WriteLine(string.Join(",", Enumerable.Range(0, 10).Select(_ => Random.Shared.Next(150))));
This generates an IEnumerable<int>
with random integers from 0 to 149 and then writes them to the Console
separated by commas.这会生成一个
IEnumerable<int>
,其中包含 0 到 149 之间的随机整数,然后将它们写入Console
,以逗号分隔。
As far as I know, there is not a method generating a list of random integers in .NET, but why won't you write your own?据我所知,.NET 中没有生成随机整数列表的方法,但你为什么不自己写一个呢? For example:
例如:
public static class MyEnumerable
{
public static IEnumerable<int> RandomEnumerable(int maxValue, int count, Random random = default)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue));
}
random ??= Random.Shared;
for (int i = 0; i < count; i++)
{
yield return random.Next(maxValue);
}
}
}
Now you can do your task in two lines like in phyton:现在你可以像在 phyton 中那样用两行来完成你的任务:
var randomList = MyEnumerable.RandomEnumerable(150, 10).ToList();
Console.WriteLine($"[{string.Join(", ", randomList)}]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.