按名称C#查找列表

时间:2013-03-24 12:30:03

标签: c# list

我有一系列列表,我想创建一个方法,它将按名称查找列表并返回列表。列表存储在类本身中。

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

请将代码保留为最简单的方法..

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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");

答案 2 :(得分:-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");
    }

}

现在您可以在代码中轻松,干净地使用它

        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");