C#中怎样将数组的顺序打乱随机排序
<h1>场景</h1><p>在ZedGraph随机天生颜色时需要从颜色数组中取颜色对象。</p>
<p>Color数组存取的是System.Drawing.Color的颜色。</p>
<p>其序次是相邻的颜色,颜色差距不大,在取颜色时按序次取颜色时,如果颜色条数比较少,差距会不显着。</p>
<p></p>
<p> </p>
<p> </p>
<p><img/></p>
<p>需要将此数组的序次打乱,随机举行排序。</p>
<p>博客主页: <br /><a href="https://blog.csdn.net/badao_liumang_qizhi">https://blog.csdn.net/badao_liumang_qizhi</a>
<h1>实现</h1>
<p>起首附从System.Drawing.Color中获取全部Color对象</p>
//用于存取取出的颜色对象
List<Color> colorList = new List<Color>();
//通过GetMember获取全部的公共成员
foreach (var item in typeof(Color).GetMembers())
{
//只取属性且为属性中的已知Color,剔除byte属性以及一些布尔属性等(A B G R IsKnownColor Name等)
if (item.MemberType == System.Reflection.MemberTypes.Property && System.Drawing.Color.FromName
(item.Name).IsKnownColor == true)
{
Color color = System.Drawing.Color.FromName(item.Name);
colorList.Add(color);
}
}
//转成数组
Color[] colors = colorList.ToArray();
<p>然后举行随机打乱序次排序</p>
colors = GetDisruptedItems(colors);
<p>调用乱序方法</p>
private static Color[] GetDisruptedItems(Color[] colors)
{
//天生一个新数组:用于在之上盘算和返回
Color[] temp;
temp = new Color;
for (int i = 0; i < temp.Length; i++)
{
temp = colors;
}
//打乱数组中元素序次
Random rand = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < temp.Length; i++)
{
int x, y; Color t;
x = rand.Next(0, temp.Length);
do
{
y = rand.Next(0, temp.Length);
} while (y == x);
t = temp;
temp = temp;
temp = t;
}
return temp;
}
<p>这里根据需要修改为自己需要的对象,获取将其直接改为泛型。</p>
页:
[1]