tags:

views:

116

answers:

4

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 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>();}
+4  A: 

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!

Pwninstein
+1  A: 

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>();
}
bitbonk
+5  A: 

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" );
TcKs
Why don't you use the boolean returned by `TryGetValue()` in your `if` statement?
Lucero
Because the "myDictonary" can have value "NULL" for the specified key. And I want to have not-NULL list in it. In fact, in this situation, is the return value useless.
TcKs
btw. why downvote?
TcKs
A: 

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.

WiseGuyEh