C# 字符串数组 随机排序,该如何处理
C# 字符串数组 随机排序例如:for(int i0i20i++){string[] LastNameList new string[]{张,王,李
C# 字符串数组 随机排序 例如:
for(int i=0;i<20;i++){ string[] LastNameList =new string[] {"张","王","李","刘","陈","杨","黄","孙","周","吴","徐","赵"}; LastNameList=LastNameList.OrderBy().ToArray(); string myLastName=LastNameList[i]; }我想要实现的功能是,每次循环时,myLastName的值是随机的。 C#
[解决办法] int n= LastNameList.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for(...)
{
int rnd = random.Next(0,n);
result += LastNameList[rnd];
}
[解决办法] 引用: 例如: for(int i=0;i<20;i++){ string[] LastNameList =new string[] {"张","王","李","刘","陈","杨","黄","孙","周","吴","徐","赵"}; LastNameList=LastNameList.OrderBy().ToArray(); string myLastName=LastNameList[i]; } 我想要实现的功能是,每次循环时,myLastName的值是随机的。 不用循环吧。只需要随机生产一个数组索引不就是随机值了。LastNameList[i];i变量为0-LastNameList.length-1的一个随机数就行了。
[解决办法] 追问
~unchecked
是什么意思。
回答
Ticks是 long 类型,强制到 int 类型肯能报错, 所以加上 ~unchecked 可以避免报错