C#: Elegant code for getting a random value from an IEnumerable

前端 未结 4 940
暗喜
暗喜 2020-12-10 11:46

In Python, I can do this:

>>> import random
>>> ints = [1,2,3]
>>> random.choice(ints)
3

In C# the first thing I

4条回答
  •  感动是毒
    2020-12-10 12:07

    No, that's basically the easiest way. Of course, that's only semi-random, but I think it fits most needs.

    EDIT: Huge Point Here...

    If you only want ONE value randomly chosen from the list... then just do this:

    var myRandomValue = ints[(new Random()).Next(0, ints.Length)];
    

    That's a O(1) operation.

提交回复
热议问题