1

好吧,我几乎是 c# 的新手,我无法弄清楚多级数组在 c# 中是如何工作的。

我制作了一个带有菜单的treeView,例如:


  • 菜单_1
  • --child_1.1
  • --child_1.2
  • ----child_1.2.1
  • ----child_1.2.2
  • ----child_1.2.3
  • --child_1.3
  • 菜单_2
  • --child_2.1
  • --child_2.2
  • ----child_2.2.1

每个 MenuItem 都应该有 6 个属性/属性/值,如下所示:

Item = { ID:int , "NAME:String , POSITION:String , ACTIVE:Bool , ACTION:bool , PATH:string }

所以 :

Menu_1 = { 1, "File", "1", true, false, "" }
child_1.1 = { 2, "Open", "1.1", true, true, "./open.exe" }

... 等等

至今 :

我已经为菜单项手动设置了一些字符串数组(String[])并用信息填充它。

String[] Item_1 = {"1", "File", "1", "1", "0", ""};
String[] Item_2 = ...

...

现在我想将所有这些字符串数组放入ArrayList[]Sort()中,使用每个 Item 的“POSITION”值(Item_1[2]

我还希望代码动态地创建项目本身的数组,从 sql 表中读取值。这些数组不应该只是我现在所做的字符串数组,因为我希望 ID 保持一个 int 并且 ACTIVE 和 ACTION 值保持一个布尔值。

最终产品应如下所示:

MenuItems = ArrayList(
    item_1 = Array(Int, String, String, Bool, Bool, String)  // \
    item_2 = Array(Int, String, String, Bool, Bool, String)  //  \
    item_3 = Array(Int, String, String, Bool, Bool, String)  //  / all sortet by the 3rd value, the position )
    item_4 = Array(Int, String, String, Bool, Bool, String)  // /
    ...
    )
)

感谢所有可以帮助我的人。

4

2 回答 2

0

假设您使用的是 C# 2.0 或更高版本,我将使用通用列表而不是 ArrayList 和类容器而不仅仅是数组。假设您使用的是 .NET 3.5 或更高版本,我建议您也使用 LINQ 进行排序。

首先,为菜单项的类型创建一个类容器:

public class MenuItem
{
    public int ID {get;set;}
    public string Name {get;set;}
    public string Position {get;set;}
    public bool Active {get;set;}
    public bool Action {get;set;}
    public string Path {get;set;}
} 

然后您可以将此类的实例存储在通用列表中:

var items = new List<MenuItem>();
items.Add(new MenuItem{ID="1", Name="File", Position="1", Active=true, Action=false, Path=""});

然后,要按位置对该列表进行排序,您可以使用 LINQ:

var sorted = items.OrderBy(i => i.Position);
于 2012-03-08T14:41:21.003 回答
0

你不能单独使用数组来做到这一点。如果您想灵活一些,请创建一个包含子项的类作为数组或列表

public class MenuItem
{
    public MenuItem()
    {
        SubItems = new List<MenuItem>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
    public bool Active { get; set; }
    public bool Action { get; set; }
    public string Path { get; set; }
    public List<MenuItem> SubItems { get; private set; }
}

然后您可以像这样添加子项

var child_1_1 = new MenuItem{ 2, "Open", "1.1", true, true, "./open.exe" };
Menu_1.SubItems.Add(child_1_1);
于 2012-03-08T14:50:03.593 回答