Home > OS >  output whole list in C#
output whole list in C#

Time:12-13

in python language i can easily do this and output is whole list:

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? Because output seperates my list's elements.

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

CodePudding user response:

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.

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.

CodePudding user response:

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? 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:

var randomList = MyEnumerable.RandomEnumerable(150, 10).ToList();
Console.WriteLine($"[{string.Join(", ", randomList)}]");
  • Related