Fill <int> List with LINQ

In python, you can do something like this:

arr = list(set(randint(-50, 50) for _ in range(10)))

I know how to program an extension method that populates an array, list, or whatever you need with random values. I find it cumbersome though, and I really admire how you can do this in python. Although, I only know Enumerable.Range,which can only be used to create fixed sequences, as far as I know.

Is this also possible in C #?

+5
source share
4 answers

You can do the following:

Random rnd = new Random();
List<int> = Enumerable.Range(0,10).Select(n => rnd.Next(-50, 51)).ToList();
+10
source
var r = new Random();

var l = Enumerable.Range(10).Select(x => r.Next(100) - 50).ToList();
+2
source

, - ...

Random r = new Random();
var ints = Enumerable.Range(0, 50).OrderBy(i => r.Next());
+2

, , :

    public static IEnumerable<int> RandomSequence(int minValue, int maxValue)
    {
        Random r = new Random();
        while (true)
            yield return r.Next(minValue, maxValue);
    }

:

    var numbers = RandomSequence(-50, 50).Take(10));

    foreach(var number in numbers)
        Console.WriteLine(number);

yield return... hehe c ",)

+1

All Articles