开发者

Cannot copy Dictionary 'Value' to a List - C#

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.


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.


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
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜