C# -Random Numbers and Enumrable

Shervan360 1,661 Reputation points
2023-02-08T17:00:08.7266667+00:00

Hi,

Could you please explain the below query? What is the relationship between a list, s, and random numbers?

Is the Range method simulated for loop here? Do we use the Range method instead of for loop?

Isn't it better to discard the s variable in the Select method?

I really appreciate any help you can provide.

  static void Main(string[] args)
        {
            var rand = new Random();
            IEnumerable<int> list = Enumerable.Range(100, 5); // Is this simulate for loop?
            var r = list.Select(s => rand.Next(-20, 31)).ToArray(); // I'm confused here.
            foreach (var item in r)
            {
                Console.WriteLine(item);
            }
        }
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-02-08T18:24:39.15+00:00

    Range(100,5) creates a collection of 5 ints starting at 100 = [100,101,102,103,104]

    Next(-20,31) return a random number between -20 and 31

    Select uses a lambda with the parameter of the collection type

    so r = will be an int array of 5 random numbers between -20 and 31

    in the sample code the values of list are not used, only the count, so not sure why a starting value of 100 instead of 0 or 1 was specified.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.