Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to populate empty list of Guids with random values

Tags:

c#

linq

var ids = new List<Guid>(count);

I have a multiple items empty list and I am looking for an elegant way to fill it with random Guids, without using for loop, preferably one-liner.

like image 667
Andrei Karcheuski Avatar asked Sep 05 '25 03:09

Andrei Karcheuski


1 Answers

Inefficient but one line:

var list = Enumerable.Range(0, count).Select(_ => Guid.NewGuid()).ToList();

Much more efficient:

var list = new List<Guid>(count);
for (int i = 0 ; i < count ; i++) list.Add(Guid.NewGuid());

If the list already exists, then... just use the second version. You can probably force LINQ to do it without using a loop in your code, but: don't do that. You are looping here, so ... use a loop! Moving the loop into LINQ doesn't improve things - it just makes it harder to read and less efficient to execute.

like image 142
Marc Gravell Avatar answered Sep 08 '25 00:09

Marc Gravell