[英]How to Sort 4 Colors in C# using Array List and Loops?
我一直在尋找一種按給定順序對“顏色”或“字符串”進行排序的算法。
這是我的代碼
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var colors = new ArrayList() { Color.White, Color.Green, Color.Blue, Color.Red};
int left = 0;
int right = colors.Count - 1;
int i = 0;
while (i <= right)
{
Color current = (Color)colors[i];
if (current == Color.Red)
{
Color temp = current;
colors[i] = colors[left];
colors[0] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
else if (current == Color.Green)
{
Color temp = current;
colors[i] = colors[right];
colors[right] = temp;
Console.WriteLine(colors[i]);
right -= 1;
}
else if (current == Color.White)
{
Color temp = current;
colors[i] = colors[left];
colors[left] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
else if (current == Color.Blue)
{
Color temp = current;
colors[i] = colors[left];
colors[left] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
//i += 1;
}
}
}
}
上面代碼的結果是:
Color [White]
Color [Red]
Color [Red]
Color [Blue]
我希望結果是:
Color [Red]
Color [White]
Color [Blue]
Color [Green]
另外,我想將它們推入 arrays,我首先需要知道的是按照給定的順序對這些顏色/字符串進行排序。 有人可以指導或幫助我嗎? 謝謝!
編輯
最近,我的代碼是:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var colors = new ArrayList() { Color.Red, Color.White, Color.Blue, Color.Green };
int left = 0;
int right = colors.Count - 1;
int i = 0;
while (i <= right)
{
Color current = (Color)colors[i];
if (current == Color.Red)
{
Color temp = (Color)colors[i];
colors[i] = colors[left];
colors[left] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
else if (current == Color.Green)
{
Color temp = (Color)colors[i];
colors[i] = colors[right];
colors[right] = temp;
Console.WriteLine(colors[i]);
right -= 1;
}
else if (current == Color.White)
{
Color temp = (Color)colors[i];
colors[i] = colors[left];
colors[left] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
else if (current == Color.Blue)
{
Color temp = (Color)colors[i];
colors[i] = colors[left];
colors[left] = temp;
Console.WriteLine(colors[i]);
i += 1;
left += 1;
}
else
{
i += 1;
}
}
}
}
}
結果是我期望的順序:
Color [Red]
Color [White]
Color [Blue]
Color [Green]
現在,我將 ArrayList 值更改為隨機排序的值。 我無法解決問題。
您可以嘗試將 colors映射到int
,然后比較這些int
,例如
// Map : each Color has its index within order array
// if you want to add Yellow, put it to the right place
Color[] order = new Color[] {
Color.White, Color.Red, Color.Blue, Color.Green
};
然后有
List<Color> colors = new List<Color>() {
Color.White, Color.Green, Color.Blue, Color.Red
}
您可以按如下方式對其進行排序:
colors.Sort((a, b) => order.IndexOf(a).CompareTo(order.IndexOf(b)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.