IcyPopTarts IcyPopTarts -4 years ago 66
C# Question

Sequence Contains No Elements Error In C#

I am making an API call and an error of

sequence contains no elements
in my syntax below I am using
.First()
but when using
.FirstOrDefault()
I get the same error. How should this syntax be changed so that this error is not presented?

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

Answer Source

You should be checking for a null object:

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();
    }
} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download