C# 基于数组生成选项列表
我该怎么做这个列表呢?我需要所有的组合C# 基于数组生成选项列表,c#,arrays,list,C#,Arrays,List,我该怎么做这个列表呢?我需要所有的组合 string[] list = { "Open", "Completed","Rescheduled", "Canceled", "Started", "Customer notified", "Do Not Move", "Needs Confirmation" }; 这个列表是前15个,有超过200个组合 打开 完成 打开,完成 重新安排 开放,重新安排 已完成,重新安排 打开、完成、重新安排 取消 打开,取消 完成取消 打开、完成、取消 重
string[] list = { "Open", "Completed","Rescheduled", "Canceled", "Started",
"Customer notified", "Do Not Move", "Needs Confirmation" };
这个列表是前15个,有超过200个组合
不要使用列表。尝试使用枚举和属性标志,如:
[Flags]
public enum Status
{
Open = 0x01,
Completed = 0x02,
Rescheduled = 0x04,
Canceled = 0x08,
Started = 0x10,
Customer_Notified = 0x20,
Do_Not_Move = 0x40,
Needs_Confirmation = 0x80
}
然后您可以一次设置几个状态,如字段
var status = Status.Open | Status.Completed
这里有一种使用字符串将其可视化的方法。数组中的每个点都可以看作二进制数中的一位(0或1)。如果所有位都打开,这将为您提供最大组合数。因此,您将从1迭代到max number,并包括数组中以该数字的二进制形式切换的值:
private void button1_Click(object sender, EventArgs e)
{
string[] list = { "Open", "Completed","Rescheduled",
"Canceled", "Started", "Customer notified",
"Do Not Move", "Needs Confirmation" };
string binary;
int max = (int)Math.Pow(2, list.Length);
List<string> combo = new List<string>();
List<string> combinations = new List<string>();
for(int i = 1; i < max; i++)
{
binary = Convert.ToString(i, 2); ' convert it to a binary number as a string
char[] bits = binary.ToCharArray();
Array.Reverse(bits);
binary = new string(bits);
combo.Clear();
for(int x = 0; x < binary.Length; x++)
{
if (binary[x] == '1')
{
combo.Add(list[x]);
}
}
combinations.Add(String.Join(", ", combo));
}
// ... do something with "combinations" ...
listBox1.DataSource = null;
listBox1.DataSource = combinations;
}
下面是一个您可能会觉得有用的位标志。您是如何生成这15个选项的列表的?例如,#2是
已完成的
但是已完成的“
不在您的字符串[]列表中
。。。您的15个组合列表并非如您所要求的“所有组合”。很抱歉,我错过了数组中的一个字符串。可能是的重复。您确定吗?列表状态=新列表();对于(inti=1;i<16;i++){statuses.Add((Status)i);},您拥有所有状态。在调试模式下尝试。我需要能够将其放在下拉列表中,并将数字1-230ish发送到db,以便我的应用程序可以基于数字访问部件。list status=new list();对于(int i=1;i<16;i++){statuses.Add((Status)i);}foreach(var Status in statuses){string test=Status.ToString();}
或者,您可以使用Description atribute获取另一个字符串。一旦超过四个值,您的标志值将出错,因为0x16不等于16(十进制)!删除每个值之前的0x
。。或者至少将其扩展出几个项目,以便人们可以看到值的模式:1、2、4、8、16、32、64、128
与0x1、0x2、0x4、0x8、0x10、0x20、0x40、0x80
[Flags]
public enum Status
{
Open = 1,
Completed = 2,
Rescheduled = 4,
Canceled = 8,
Started = 16,
Customer_Notified = 32,
Do_Not_Move = 64,
Needs_Confirmation = 128
}
private void button2_Click(object sender, EventArgs e)
{
List<string> combinations = new List<string>();
Status status;
int max = (int)Math.Pow(2, Enum.GetValues(typeof(Status)).Length);
for(int i = 1; i < max; i++)
{
status = (Status)i;
combinations.Add(status.ToString().Replace("_", " "));
}
listBox1.DataSource = null;
listBox1.DataSource = combinations;
}