【问题标题】:Concatenate dictionary keys separated by comma's连接用逗号分隔的字典键
【发布时间】:2013-03-01 10:23:21
【问题描述】:

我正在寻找一种更好的方法来连接字典键,这就是我现在正在做的事情:

Dictionary<int, string> myList = new Dictionary<int, string>();

myList.Add(1, "value");
myList.Add(2, "value");
myList.Add(3, "value");
myList.Add(4, "value");

string choices = "";

foreach (int key in myList.Keys)
{
    choices += key + " ";
}

choices = "(" + choices.Trim().Replace(" ", ",") + ")"; // (1,2,3,4)

我确定有更好的方法,也许是 LINQ?

【问题讨论】:

    标签: c# string dictionary concatenation comma


    【解决方案1】:

    你可以使用:

    Dictionary<int, string> myList = new Dictionary<int, string>();
    
    myList.Add(1, "value");
    myList.Add(2, "value");
    myList.Add(3, "value");
    myList.Add(4, "value");
    
    choices = String.Format("({0})", string.Join(",", myList.Keys));
    

    【讨论】:

      【解决方案2】:
      string.Format("({0})", string.Join(",", myList.Keys));
      

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 2020-02-13
        • 2021-09-05
        • 2021-05-18
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        相关资源
        最近更新 更多