【问题标题】:From Dictionary to List从字典到列表
【发布时间】:2012-09-01 01:04:53
【问题描述】:

这是一本字典:

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();

我想要执行以下操作:当我单击按钮时,第一个字典 (Dic) 键及其值被复制到列表 (List&lt;string&gt;)。再次单击,同样的事情发生了,但这次是下一个字典键和值。

【问题讨论】:

  • 对不起,我不明白你的问题。您的意思是要向字典添加列表吗?或者您在访问 List 时遇到问题?
  • 字典中没有明确的顺序。
  • Hydev, no ) 我想将 Dictionary 中的元素复制到 List
  • 如果您在每次点击后添加一个包含字典内容和列表内容的示例,帮助您会简单得多...

标签: c# dictionary


【解决方案1】:

看起来您想根据字典列表值中的所有字符串元素创建一个新的List&lt;string&gt;。您可以使用SelectMany 将其展平并使用以下代码获取列表:

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();
Dic.Add("1", new List<string>{"ABC","DEF","GHI"});
Dic.Add("2", new List<string>{"JKL","MNO","PQR"});
Dic.Add("3", new List<string>{"STU","VWX","YZ"});

List<string> strList = Dic.SelectMany(r => r.Value).ToList();

其中strList 将在单个列表中包含字典中的所有字符串项。

【讨论】:

    【解决方案2】:

    为什么不使用ToList 方法?

    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary["cat"] = 1;
    dictionary["dog"] = 4;
    dictionary["mouse"] = 2;
    dictionary["rabbit"] = -1;
    
    // Call ToList.
    List<KeyValuePair<string, int>> list = dictionary.ToList();
    
    // Loop over list.
    foreach (KeyValuePair<string, int> pair in list)
    {
        Console.WriteLine(pair.Key);
        Console.WriteLine("   {0}", pair.Value);
    }
    

    【讨论】:

    • 我有 Dictionary> Dic = new Dictionary>();---------------- -- no Dictionary dictionary = new Dictionary();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多