Using LINQ to generate a random size collection filled with random numbers

I am studying LINQ right now, and I am wondering if there is a way to use it to actually generate a list, and not just request an already generated list. So I have the following code using for a loop to get a list of random numbers from int and fill it with random numbers, is there anyway to convert it to LINQ?

var ret = new List<int>(); for (var i = 0; i < _rand.Next(100); i++) ret.Add(_rand.Next(10)); 
+4
source share
5 answers

You can do it:

 Random _rand = new Random(); var results = Enumerable.Range(0, _rand.Next(100)) .Select(r => _rand.Next(10)) .ToList(); 
+7
source

You can do it as follows:

 List<int> result = Enumerable.Range(0, _rand.Next(100)) .Select(x => _rand.Next(10)) .ToList(); 

Using LINQ here will give lower performance, and I'm not sure if this improves readability. It would be best to do this as follows:

 int length = _rand.Next(100); for (var i = 0; i < length; i++) { ret.Add(_rand.Next(10)); } 
+3
source

Btw, I think in your original solution you are not getting exactly what you expect, since _rand.Next (100) is evaluated for each iteration of the loop. Thus, the length of the list does not have a uniform distribution in [0; 100)

+2
source

You can use NBuilder :

 var random = new Random(); var list = Builder<int>.CreateListOfSize(random.Next()) .WhereAll() .HaveDoneToThem(x => random.Next()) .Build(); 

The advantage of NBuilder is that you can use it not only to easily create large lists of primitives (trivial), but also to easily create large lists of complex types (not so trivial):

 var list = Builder<Product>.CreateListOfSize(100) .WhereAll() .HaveDoneToThem(x => x.Name = GetRandomName()) .And(x => x.Cost = GetRandomCost()) .Build(); 
+2
source

I think it is not elegant to first generate a sequence of numbers, just to throw it away. These methods deliver random numbers in place (you need to pay in detail):

 IEnumerable<int> GetRandomSequence(int maxNumber) { var random = new Random(); while (true) yield return random.Next(maxNumber); } IEnumerable<int> GetRandomSequence(int maxNumber, int maxCount) { return GetRandomSequence(maxNumber).Take(maxCount); } var random = new Random(); var list = GetRandomSequence(100, 10).ToList (); 

And I like how I can write the same thing in F #:

 let random = new Random (); let list = Seq.init (random.Next 10) (fun _ -> random.Next 100) |> List.ofSeq; 
+2
source

Source: https://habr.com/ru/post/1338509/


All Articles