chillydk147
chillydk147

Reputation: 385

Randomize but exclude the random variable

I have some code to randomize an extracted list of results but I'd prefer to not include the random variable as part of the extracted result, any ideas? Here's my code:

var rnd = new Random();

var numList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var extracted = (from n1 in numList
                 from n2 in numList
                 from n3 in numList
                 from n4 in numList
                     where n1 + n2 + n3 + n4 > 20
                 select new { n1, n2, n3, n4, Rnd = rnd.NextDouble() })
                 .OrderBy(z => z.Rnd).ToList();

Upvotes: 1

Views: 75

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236288

If you need to randomize output, just order by random values, without including them in selected data:

var rnd = new Random();
var numList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var extracted =  from n1 in numList
                 from n2 in numList
                 from n3 in numList
                 from n4 in numList
                 where n1 + n2 + n3 + n4 > 20
                 orderby rnd.NextDouble()
                 select new { n1, n2, n3, n4 }; // you can use ToList() 

Upvotes: 2

Related Questions