2017-01-30 63 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();