如何在某些条件下将列表添加到列表中?

时间:2015-07-16 09:26:53

标签: c#

所以,如果我有这个:

public MainMenuModel(string transKey, string stateName, string displayUrl, bool hasSubMenu= false,List<SubMenuModel>subMenu=null)
{
            TransKey = transKey;
            StateName = stateName;
            DisplayUrl = displayUrl;          
            HasSubMenu = hasSubMenu;
            SubMenu = subMenu;             
}
        public string TransKey { get; set; }
        public string StateName { get; set; }
        public string DisplayUrl { get; set; }

        public bool HasSubMenu { get; set; }

        public List<SubMenuModel>SubMenu { get; set; }

}



public class SubMenuModel
{
            public SubMenuModel(string transKey, string stateName, string displayUrl)
            {
                TransKey = transKey;
                StateName = stateName;
                DisplayUrl = displayUrl;              
            }
            public string TransKey { get; set; }
            public string StateName { get; set; }
            public string DisplayUrl { get; set; }


}

如何在SubMenu中添加MainMenu某些条件,例如:

if(test!=null)
{
    SubMenu.Add(new SubMenuModel("PERSONAL_INFORMATION","account.personalinformation","/account/personalinformation"));
}
SubMenu.Add(new SubMenuModel("NOTIFICATIONS", "account.notificationsettings", "/account/notifications"));
SubMenu.Add(new SubMenuModel("CHANGE_PASSWORD", "account.changepassword", "/account/passwordchange"));
SubMenu.Add(new SubMenuModel("GAME_SETTINGS", "default", "default"));

MainMenu.Add(SubMenu) - &gt;这不起作用...如何在主菜单中添加条件子菜单?我也试过了MainMenu.AddRange(SubMenu),但我不能这样做,因为它的类型不同。我试过这样的事情:

for (int i = 0; i < SubMenu.Count; i++)
{
   MainMenu[0].SubMenu.Add(SubMenu[i]);
}

但是我收到了一个错误。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

为什么不能创建元素MainMenu然后添加条件?

MainMenuModel model = new MainMenuModel("TransKey", "StateName", "DisplayUrl");
if(condition) {
  model.SubMenu.Add(new SubMenuModel("GAME_SETTINGS", "default", "default"));
}

另一种简单的方法是创建一个方法:

public void AddSubMenu(bool condition, SubMenuModel subMenu) {
    if(condition)
        SubMenu.Add(subMenu);
}

或者你需要在SubMenuModel类中添加一个新属性来放置条件以使其成为模型的一个特征,例如一个整数:

public int Condition { get; set; }

然后在MainMenuModel中,您可以像下面那样管理Add方法:

public void AddSubMenu(bool condition, SubMenuModel subMenu) {
    if(condition)
        SubMenu.Add(subMenu);
}

或仅创建一个只读的新属性以获取仅可用的子菜单:

public List<SubMenuModel> AvailableSubMenu { 
    // Consider sm.Condition is an integer and we want only the positive ones
    get { return SubMenu.FindAll(sm => sm.Condition > 0);
}

通过这种方式,您将只获得满足条件的SubMenuModel。

答案 1 :(得分:1)

因为在MainMenuModel中你已经有了

public List<SubMenuModel> SubMenu { get; set; }

所以,就这样做吧

MainMenu[positionOfDataInList].SubMenu = subMenuToAdd;

如果您要添加更多SubMenu,请执行

MainMenu[positionOfDataInList].SubMenu.AddRange(anotherSubMenu);