开发者

How to create List while program is running

While my program is running it receives messages with Id's and data in one message.

I want to make a new List for every Id where I can store the data from that Id. The 开发者_JAVA技巧problem is that I don't know how many Id's I wil receive until my program is running. The only thing I know is that it's a lot. So I don't know if it is possible or how I should do this. This is wat I'm basically trying to do:

if (!(idlist.Contains(id))){

 idlist.Add(id);
 List<string> id.ToString() = new List<string>();}


Use Dictionary:

var myDictionary = new Dictionary<int, List<string>>();
// .....
List<string> myList;
myDictionary.TryGetValue( id, out myList );
if ( null == myList ) {
    myList = new List<string>();
    myDictionary[id] = myList;
}
myList.Add( "hello world" );


You can do something like:

Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>();
dictionary[newId] = new List<string>();
dictionary[newId].add("Hello!");

Dictionaries are quite handy!

You can do something like this as well:

if(!dictionary.ContainsKey(newId)){
    //Add the new List<string> to the dictionary
}else{
    //Add to the existing List<string> at dictionary[newId]
}

Hope this helps!


You can use Dictionary that can store a list of Key-Value-Pairs. Your key would be the id and the value would be the list of strings.

Dictionary<int,List<string>> ids = new Dictionary<int,List<string>>();

And when you get an ID you create a new entry like this:

ids[id] = new List<string>();

If the dictionary already contained a entry for this ID it will be overwritten. You can check using ContainsKey to prevent that:

if(!ids.ContainsKey(id))
{
    ids[id] = new List<string>();
}


I dont believe you can create a list the way you are attempting. What you might like to try is something like this:

IDictionary<int, List<string>> idDictionary = new Dictionary<int, List<string>>()
//wait for messages
...
//handle new message
if (!idDictionary.containsKey(incommingId)){
     idDictionary.add(incommingId, new List<String>())
}
idDictionary[incommingId].add(data);

Using a dictionary to hold the data lists for all received id's should provide decent lookup performance. However this may change if you receive many hundreds of different id's when the program is running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜