Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill List<int> using LINQ

Tags:

c#

random

linq

In python you can do something like this:

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

I do know how to program a extension method that fills a array, list or whatever you need with random values. I find this cumbersome though, and I really admire how you can do it in python. Although, I only know of Enumerable.Range, which only can be used for generating fixed sequences, to my knowledge.

Is it possible in C# as well?

like image 387
CasperT Avatar asked Aug 17 '09 11:08

CasperT


1 Answers

You could do like this:

Random rnd = new Random();
List<int> = Enumerable.Range(0,10).Select(n => rnd.Next(-50, 51)).ToList();
like image 181
Guffa Avatar answered Nov 07 '22 02:11

Guffa