C# 随机打乱数组
把
电子磅秤,1吨电子磅秤,2吨电子磅秤,3吨电子磅秤
改成
1吨电子磅秤,3吨电子磅秤,2吨电子磅秤,电子磅秤
private void button1_Click(object sender, EventArgs e)
{
string strArr = txtSource.Text.Trim();
string[] SourceStr= strArr.Split(new char[2] { ',', ',' }); //支持中英文逗号
string[] NewStr = RandomSort(SourceStr);
string strResult="";
for (int i = 0; i < NewStr.Length; i++)
{
if (i == NewStr.Length - 1)
{
strResult += NewStr[i];
}
else
{
strResult += NewStr[i]+",";
}
}
txtNew.Text = strResult;
}
public static T[] RandomSort<T>(T[] array)
{
int len = array.Length;
System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
T[] ret = new T[len];
Random rand = new Random();
int i = 0;
while (list.Count < len)
{
int iter = rand.Next(0, len);
if (!list.Contains(iter))
{
list.Add(iter);
ret[i] = array[iter];
i++;
}
}
return ret;
}