错误:在集合列表中添加值时出错

时间:2015-11-02 06:42:26

标签: c# linq

我创建了List<Dictionary<string, Dictionary<string,string>>>的列表,我正在尝试在该列表中添加值。 PFB代码。

public string Get(Hello request)
{
  string html= "[{'Id':1},{'Id':2}]"; 
  List<Dictionary<string, Dictionary<string,string>>> lsData = null;
  var values = JsonConvert.DeserializeObject<List<object>>(html); //parse json Array  

 for (int i = 0; i < values.Count; i++) // loop one element on json array and parse it.
 {
   var obj = values[i];
   Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.ToString());
   lsData.Add(i, data); //Showing error here
 }
 return "success";
}

但此代码显示以下错误。The type arguments for method 'ServiceStack.ServiceRoute Extensions.Add<T>(ServiceStack.Web.IService Routes, strong, ServiceStack.ApplyTo, params System.Linq.Expressions.Expression<System.Func<T,object>>[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我不明白为什么会出现错误。提前谢谢。

2 个答案:

答案 0 :(得分:2)

问题出在此行lsData.Add(i, data);,因为您尝试将Dictionary<string, Dictionary<string,string>>添加到给定列表,现在它需要两件事:

  1. 已初步化Dictionary<string,string>,您正在按以下方式执行此操作:

    Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.ToString());
    
  2. 假设Deserialization正常工作,但是当你进行列表添加调用时,它的错误就像是为Dictionary而不是List添加值,因此请关注变化:

    在for循环中添加以下代码:

    var lsDataDictionary = new Dictionary<string, Dictionary<string,string>>();
    lsDataDictionary.Add(i.ToString(),data)
    lsData.Add(lsDataDictionary);
    

    请注意,lsDataDictionary键是字符串,for loop counter需要转换为string

答案 1 :(得分:0)

您需要实例化lsData

lsData = new List<Dictionary<string, Dictionary<string,string>>>();