【问题标题】:Convert Concurrent Dictonary values to a List将并发字典值转换为列表
【发布时间】:2017-01-23 08:04:44
【问题描述】:

如何将并发字典值转换为列表,下面是我尝试的代码。

//this collection will maitain server connections/ server can support multiple connections
public static readonly IDictionary<string, ISet<ConnectionManager>> SereverConnections = new ConcurrentDictionary<string, ISet<ConnectionManager>>();
//Get All Server Connections List
public static IList<ConnectionManager> GetAllServerConnections()
{

    IList<ConnectionManager> connectionList = new List<ConnectionManager>(Global.SereverConnections.Values);
    return connectionList;
    //return Global.SereverConnections.Values.ToList();
    //return (Gloconnections.ToList() ?? Enumerable.Empty<ConnectionManager>().ToList());
}

编译时错误:

cannot convert from 'System.Collections.Generic.ICollection<System.Collections.Generic.ISet<ChatServer.ConnectionManager>>' to 'int'

【问题讨论】:

  • 我想知道我的问题被否决的原因?有什么理由让我提高自我吗?
  • 不知道为什么你被否决了……据我所知,这不是一个不合理的问题……显然有人认为值得回答。请务必标记最适合您的答案。给某人功劳。

标签: c# list concurrentdictionary


【解决方案1】:

你试过了吗:

IList<ConnectionManager> connectionList = Global.SereverConnections.SelectMany(x=>x.Value).ToList();

【讨论】:

    【解决方案2】:
    List<ISet<ConnectionManager>> connectionList = Global.SereverConnections.Values.ToList();
    

    这将为您提供一个“ISet”列表 - 如果您需要更进一步,这真的取决于 ISet 是什么。

    【讨论】:

      【解决方案3】:

      您在 List(int size) 构造函数中传递 ICollection。当然,编译器会抱怨将 ICollection 转换为 Integer。 您还包含集合集合,因此您的注释代码将不起作用,这样您就可以获得所有不同的连接:

      public static IList<ConnectionManager> GetAllServerConnections()
      {
          return Global.SereverConnections.SelectMany(x=> x.Value).Distinct().ToList();
      }
      

      【讨论】:

      • 我试过但不接受 IList connectionList = new List(Global.SereverConnections.Values.Select(x=> x));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2016-02-04
      • 1970-01-01
      • 2022-11-14
      • 2017-04-23
      • 2021-10-13
      相关资源
      最近更新 更多