2017-01-30 67 views
0

所以我試圖打印出我的列表中的成員。我使用以下字典結構:SortedDictionary<string,List<int>>其中我使用字符串作爲關鍵字。在sortedDictionary中打印列表對象

在我的功能ShowContents我試圖打印出我在看什麼條目,以及元素的數量,以及元素是什麼。這是我掙扎的地方。我只是得到System.Collections.Generic.List1[System.Int32]而不是對象。

這裏是我當前的代碼:

SortedDictionary<string,List<int>> jumpStats = new SortedDictionary<string,List<int>>(); // jumpstats[0] == (volt, 10m) 
public string ShowContents() 
     { 
      var sb = new StringBuilder(); 
      foreach (KeyValuePair<string, List<int>> item in jumpStats) 
      { 
       sb.Append(string.Format("{0}: has {1} entries with values {2}", item.Key, item.Value.Count(), item.Value)); 
      } 
      return sb.ToString(); 
     } 
     public SortedDictionary<string,List<int>> addjumpStats() //Adding information about the jump to the dictionary 
     { 
      try 
      { 
       jumpStats.Add("Volt", new List<int>()); 
       jumpStats["Volt"].Add(12); 
       jumpStats["Volt"].Add(13); 
       jumpStats["Volt"].Add(15); 
      } 
      catch (ArgumentException) 
      { 
       Console.WriteLine("An Element already exists with the same key"); 
      } 
      return jumpStats; 
     } 

輸出示例現在:Volt: 3 System.Collections.Generic.List1[System.Int32]

+0

你在期待'item.Value'打印?想象一下,你有一個List ',而不是'List '。 –

回答

1

在您輸出item.Value這是一個List<int>因此爲什麼你看到的類名的附加功能 - List的ToString函數不知道將列表中的所有值連接在一起 - 它僅僅返回類名稱。你需要告訴它該做什麼。一個簡單的方法來做到這一點是使用的string.join:

string.Join(",", item.Value) 

而且在上下文中:

var sb = new StringBuilder(); 
foreach (KeyValuePair<string, List<int>> item in jumpStats) 
{ 
    sb.Append(string.Format("{0}: has {1} entries with values {2}", item.Key, item.Value.Count(), string.Join(",", item.Value)); 
} 
return sb.ToString();