Home > database >  How Can I randomly display/print/select 4 elements in a list without repetition in C#?
How Can I randomly display/print/select 4 elements in a list without repetition in C#?

Time:11-20

 
            List<string> topLevel = new List<string>();
            

          


            topLevel.Add("000");
            topLevel.Add("100");
            topLevel.Add("200");
            topLevel.Add("300");
            topLevel.Add("400");
            topLevel.Add("500");
            topLevel.Add("600");
            topLevel.Add("700");
            topLevel.Add("800");
            topLevel.Add("900");

I tried with while loops, for loops and LINQ, but got nothing to work

CodePudding user response:

This should do it by leveraging LINQ:

topLevel.OrderBy(x => Guid.NewGuid()).Take(4);

By sorting by Guid.NewGuid(), we are effectively randomizing the list. Afterwards, we return the top 4. If we are concerned that the list itself may contain duplicates, then we can use Distinct() to remove the duplicates:

topLevel.Distinct().OrderBy(x => Guid.NewGuid()).Take(4);

Fiddle: enter image description here

  • Related