C#

时间:2017-06-13 00:27:38

标签: c# .net linq c#-4.0

我正在使用sequence contains no elements语法进行API调用和.First()错误,但在使用.FirstOrDefault()时,我得到了同样的错误。如何更改此语法以便不显示此错误?

public class Root 
{ 
    public List<AI> AI { get; set; } 
} 
public class AI 
{ 
    public List<Dictionary<string, string>> AddressInfo { get; set; } 
} 

public class Main[] 
{ 
    var response = syncClient.DownloadString(url); 
    var returnData = JsonConvert.DeserializeObject<Root[]>(response); 
    foreach (Root ro in returnData) 
    {
        foreach (AI info in ro.AI) 
        { 
            string address = info.AddressInfo.First()["Address1"]); 
            string address2 =  info.AddressInfo.First()["Address2"]); 
            string city = info.AddressInfo.First()["City"]);
            string state =  info.AddressInfo.First()["State"]);
            string zip =  info.AddressInfo.First()["Zip"]);
            Conesole.ReadLine();
        } 
    }
}

1 个答案:

答案 0 :(得分:1)

您应该检查空对象:

foreach (AI info in ro.AI) 
{ 
    var addressInfo = info.AddressInfo.FirstOrDefault();

    if(addressInfo != null)
    {
        string address = addressInfo["Address1"]; 
        string address2 = addressInfo["Address2"]; 
        string city = addressInfo["City"];
        string state = addressInfo["State"];
        string zip = addressInfo["Zip"];

        Console.ReadLine();
    }
}