0

Consider the following

var x= doc.Descendants("a").Where(p => p.Attributes["itemprop"].Value.Contains("image")).FirstOrDefault().Attributes["href"].Value;

Descendants might return null

Where might return null

Value might return null

Attributes might Be null etc..

is a try catch my only option to set the variable to null with the linq syntax to avoid the null reference exception, i simply want to set the variable to null and i don't want to split it out and use multiple if statements to check?

try
{
  x= doc.Descendants("a").Where(p => p.Attributes["itemprop"].Value.Contains("image")).FirstOrDefault().Attributes["href"].Value;
}
catch
{
  x=null;
}
user1492051
  • 866
  • 8
  • 20

1 Answers1

2

Descendants can't return null it always return IEnumerable<T>

Where can't return null it return IEnumerable<T>

Attributes might Be null yes but you can avoid using Value you can use (string)p.Attributes["itemprop"] instead of p.Attributes["itemprop"].Value

so you can write your query as:

string val;

var x= doc.Descendants("a")
           .Where(p => (((string)p.Attributes["itemprop"]) ?? string.Empty)
                              .Contains("image"))
           .FirstOrDefault();
if(x != null)
{
    val = (string)Attributes["href"];
}
Hamlet Hakobyan
  • 31,621
  • 6
  • 49
  • 65