views:

62

answers:

2

Hello,

Having followed a tutorial I have a hashtable that contains a TcpClient object that matches with the string of a connected user. After reading about the pro's and cons of a hashtable it was recommended that using a Dictionary is preferred due to it being generic, thus more flexible.

From here an array is made that contains the Values from the hashtable, in this case the TcpClient of the users. By looping the array of TcpClients I can get the stream of each user and write a message to their screen.

Now if I try and convert the array holding the TcpClient object for each user I get the following errors:

The best overloaded method match for 'System.Collections.Generic.Dictionary.ValueCollection.CopyTo(System.Net.Sockets.TcpClient[], int)' has some invalid arguments

Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Net.Sockets.TcpClient[]'

This is the Dictionary object:

public static Dictionary<string, TcpClient> htUsers = new Dictionary<string, TcpClient>();

This is the List I create:

List<TcpClient> tcpClients = new List<TcpClient>(); 

This is the method I'm trying to follow to copy the Values to the List:

htUsers.Values.CopyTo(tcpClients,0);

Is it something that can't be done or do I need to make a simple change?

Thanks for your time.

+7  A: 

The easiest way to fix this would be to just do:

List<TcpClient> tcpClients = new List<TcpClient>(htUsers.Values);

Or:

List<TcpClient> tcpClients = new List<TcpClient>();

// Do things with list...
tcpClients.AddRange(htUsers.Values);

The CopyTo method copies into an array, not into a list.

Reed Copsey
@Jamie: Yes. It'll generate the list directly off the values, since the values implements IEnumerable<TcpClient>. I edited to add a second option (in case you're doing something else with the list in the middle)
Reed Copsey
Thanks! I probably should of realised that when looking at the error statements and the IntelliSense description. I need some more coffee.
Jamie Keeling
+2  A: 

CopyTo only copies an array to an array; in your case, you're trying to copy an array to a list. Try this instead:

List<TcpClient> tcpClients = htUsers.Values.ToList();

Note that for a lot of cases (such as enumerating), you can work directly on the dictionary:

foreach (var kvp in htUsers) {
    string user = kvp.Key;
    TcpClient client = kvp.Value;
    // do something
}
kevingessner
Thankyou for the tip! =]
Jamie Keeling