Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法复制字典';价值';到列表-C#_C#_List_Dictionary_Copy - Fatal编程技术网

无法复制字典';价值';到列表-C#

无法复制字典';价值';到列表-C#,c#,list,dictionary,copy,C#,List,Dictionary,Copy,在学习了一个教程之后,我有一个哈希表,其中包含一个TcpClient对象,该对象与连接用户的字符串相匹配。在阅读了哈希表的优缺点之后,建议使用字典,因为它是通用的,因此更灵活 从这里创建一个数组,其中包含哈希表中的值,在本例中是用户的TcpClient。通过循环TCPClient数组,我可以获得每个用户的流,并将消息写入他们的屏幕 现在,如果我尝试为每个用户转换包含TcpClient对象的数组,则会出现以下错误: 与“System.Collections.Generic.Dictionary.V

在学习了一个教程之后,我有一个哈希表,其中包含一个TcpClient对象,该对象与连接用户的字符串相匹配。在阅读了哈希表的优缺点之后,建议使用字典,因为它是通用的,因此更灵活

从这里创建一个数组,其中包含哈希表中的值,在本例中是用户的TcpClient。通过循环TCPClient数组,我可以获得每个用户的流,并将消息写入他们的屏幕

现在,如果我尝试为每个用户转换包含TcpClient对象的数组,则会出现以下错误:

与“System.Collections.Generic.Dictionary.ValueCollection.CopyTo(System.Net.Sockets.TcpClient[],int)”匹配的最佳重载方法具有一些无效参数

参数1:无法从“System.Collections.Generic.List”转换为“System.Net.Sockets.TcpClient[]”

这是Dictionary对象:

public static Dictionary<string, TcpClient> htUsers = new Dictionary<string, TcpClient>();
是不能做的事情还是我需要做一个简单的改变


谢谢您的时间。

解决此问题的最简单方法是:

List<TcpClient> tcpClients = new List<TcpClient>(htUsers.Values);
List tcpClients=新列表(htUsers.Values);
或:

List tcpClients=new List();
//用列表做事情。。。
tcpClients.AddRange(htUsers.Values);

该方法复制到数组中,而不是列表中。

CopyTo
仅将数组复制到数组中;在您的例子中,您试图将数组复制到列表中。请尝试以下方法:

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

@杰米:是的。它将直接从值生成列表,因为这些值实现IEnumerable。我编辑后添加了第二个选项(如果您正在做其他事情,列表在中间),谢谢!在查看错误语句和IntelliSense描述时,我可能应该意识到这一点。我还需要一些咖啡。
List<TcpClient> tcpClients = new List<TcpClient>(htUsers.Values);
List<TcpClient> tcpClients = new List<TcpClient>();

// Do things with list...
tcpClients.AddRange(htUsers.Values);
List<TcpClient> tcpClients = htUsers.Values.ToList();
foreach (var kvp in htUsers) {
    string user = kvp.Key;
    TcpClient client = kvp.Value;
    // do something
}