连接以逗号's分隔的字典键

本文关键字:分隔 字典 连接 | 更新日期: 2023-09-27 18:03:54

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

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也许?

连接以逗号's分隔的字典键

string.Format("({0})", string.Join(",", myList.Keys));

您可以使用:

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));