2

Good day I have this array and list and i would like to get a random value from the list

random Ram = new Random();
String[] Test= {"C2", "C3", "C4"};

List<String> LTest = new List<String>(Test);

String var = Ram.Next(LTest);

Error -cannot convert from system.collection.generic.list to 'Int'

and also i would like to continue to remove the object from the list and add it to a new one

Test.remove(Var);

newlist.add(Var);

thank you.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
keitaro martin
  • 837
  • 7
  • 7

2 Answers2

5

If you want to choose an item from the list at random, you can do it a couple ways.

You can use random to compute an integer, and use that as an index:

var index = random.Next(list.Count);
var randomItem = list[index];

Or you can just sort the list randomly and take the first one:

var item = list.OrderBy( s => random.NextDouble() ).First();

The first method is very common; the second method is handy if you expect to be picking more than one random item from the list and you wish to avoid repetition. Just take the first, second, third, etc. items.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • I think the second method is better in the case of non-indexed collections (like `IEnumerable`) because it means you don't need to access `list` twice, thereby more DRY. But for indexed collections (like `IList`), the first method should be used, otherwise it will be really slow. – Neo Apr 29 '19 at 10:13
3

Random.Next accepts a parameter of int.Also don't use var since its a reserved keyword in c#, You need

String nextVal = Ram.Next(LTest.Count);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Props for teaching me what [Contextual Keywords](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/) are in C#; I didn't realize `var` wasn't a reserved word! – Poosh Feb 15 '18 at 02:22
  • @Poosh Thanks for the headsup – Sajeetharan Feb 15 '18 at 02:25
  • I wasn't being sarcastic. I think you actually can use `var` as a variable name in that context (based on what the link says; I haven't tried it). But it may depend on the version of C#... – Poosh Feb 15 '18 at 02:26
  • yes you can , but better not – Sajeetharan Feb 15 '18 at 02:28