2013-03-13 50 views
3

我正在尋找一種更好的方式來連接字典鍵分離,這是我現在在做什麼:串聯字典鍵用逗號

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

回答

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

您可以使用:

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