2013-03-24 59 views
-6

列表我有一系列的名单,我想创建一个将找到它的名称列表,并返回列表的方法。这些列表存储在类本身中。查找其名称C#

public void AddCord(string cord, string listName) 
    { 
     List<String> myShip; 
     myShip = findListByName(listName); 
     myShip.Add(cord); 
    } 

请保持代码的最简单的方法..

+1

你已经试过了什么? – evgenyl 2013-03-24 12:31:46

+1

也许你应该展示这些列表是如何存储的以及这个名字的来源?它是列表的名称,还是列表中某艘船的名称,或者是您要搜索的内容?您是否尝试过实施它?如果是这样,代码是什么样的? – 2013-03-24 12:31:53

+0

你好,对不起,如果我不清楚 的列表存储在类,然后在类中构造像这样: 级战列舰 {// 属性,玩家船舶 私人列表 _playerCarrierA; 私人列表 _playerDestroyerA; 公共战舰() { _playerCarrierA =新列表(); _playerDestroyerA =新列表(); } 有比这更多的名单,基本上我想要检索其名称的列表的方法,然后将字符串添加到该列表。 我已经尝试了很多方法,没有一个是成功的。 – Kehza 2013-03-24 12:45:55

回答

2

试试这个:

//Create global dictionary of lists 
Dictionary<string, List<string> dictionaryOfLists = new Dictionary<string, List<string>(); 

//Get and create lists from a single method 
public List<string> FindListByName(string stringListName) 
{ 
    //If the list we want does not exist yet we can create a blank one 
    if (!dictionaryOfLists.ContainsKey(stringListName)) 
     dictionaryOfLists.Add(stringListName, new List<string>()); 

    //Return the requested list 
    return dictionaryOfLists[stringListName]; 
} 
+0

哦,辉煌的,这可能只是工作:D感谢虐待现在尝试它 – Kehza 2013-03-24 12:47:50

1
Dictionary<string, List<string>> myRecords=new Dictionary<string, List<string>>(); 

if(!myRecords.ContainsKey("abc")) 
{ 
    List<string> abcList=new List<string>(); 
    myRecords.Add("abc", abcList); 
} 
else 
    myRecords.["abc"].Add("a"); 
+0

非常感谢,从来没有遇到字典之前:) – Kehza 2013-03-24 12:55:09

-1

这就是我的回答,在我眼里多了几分乐趣一个解决方案:d

class MyList<T> : List<T> 
{ 
    static List<object> superlist; 

    public string name; 

    ~MyList() { 
     if (superlist != null) 
     superlist.Remove(this); 
    } 

    public MyList(string name) 
     : base() { 
     init(name); 
    } 

    public MyList(string name, int cap) 
     : base(cap) { 
     init(name); 
    } 

    public MyList(string name, IEnumerable<T> IE) 
     : base(IE) { 
     init(name); 
    } 

    void init(string name) { 
     if (superlist == null) 
      superlist = new List<object>(); 

     this.name = name; 
     superlist.Add(this); 
    } 

    public static void AddToListByName(T add, string listName) { 
     for (int i = 0; i < superlist.Count; i++) { 
      if (superlist[i].GetType().GenericTypeArguments[0] == add.GetType() && ((MyList<T>)(superlist[i])).name == listName) { 
       ((MyList<T>)(superlist[i])).Add(add); 
       return; 
      } 
     } 
     throw new Exception("could not find the list"); 
    } 

} 

现在你可以很容易地使用它和cle anly in your code

 MyList<string> a = new MyList<string>("a"); 
     MyList<string> b = new MyList<string>("b"); 

     a.Add("normal add to list a"); 

     MyList<string>.AddToListByName("hello add to a", "a"); 
     MyList<string>.AddToListByName("hello add to b", "b"); 
+0

我认为使用静态方法是一个巨大的代码气味。有一个析构函数*真的会引发红旗 – ANeves 2015-01-29 12:22:31