none
How to check for Empty when extracting SdtBlock RRS feed

  • Question

  • I have the following code which works perfect if the document contains the content control which has tag name same as the variable value.

    mainPart.Document.Body.Descendants<sdtblock>().Where(r => r.SdtProperties.GetFirstChild<tag>().Val == myVar).Single();</tag></sdtblock>

    But this line throws a Sequence is Empty exception if the document does not contain any content control which has the Tag/Title of the variable value.

    Can you please tell me how to build some resiliency in the code?


    MSDNStudent Knows not much!



    • Edited by MSDN Student Thursday, February 16, 2012 8:27 PM
    Thursday, February 16, 2012 12:55 PM

Answers

  • Hi,

    You can use Try Catch statement to prevent getting a exception if the document doesn't contain any Content Controls or there is a content control whose tag name matches what you specify, see:

           SdtBlock block = null;
                try
                {
                    block = body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == var).First();
                }
                catch
                {
                }
                if (block != null)
                {
                    block.SdtProperties.GetFirstChild<Tag>().Val = "MyCustomTag";
                }

    i hope this helps.


    Calvin Gao[MSFT]
    MSDN Community Support | Feedback to us

    Friday, February 17, 2012 5:48 AM
    Moderator
  • I am currently using FirstOrDefault method. this is causing the error to stop

    MSDNStudent Knows not much!

    Friday, February 17, 2012 11:18 AM

All replies

  • Hi,

    You can use Try Catch statement to prevent getting a exception if the document doesn't contain any Content Controls or there is a content control whose tag name matches what you specify, see:

           SdtBlock block = null;
                try
                {
                    block = body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == var).First();
                }
                catch
                {
                }
                if (block != null)
                {
                    block.SdtProperties.GetFirstChild<Tag>().Val = "MyCustomTag";
                }

    i hope this helps.


    Calvin Gao[MSFT]
    MSDN Community Support | Feedback to us

    Friday, February 17, 2012 5:48 AM
    Moderator
  • I am currently using FirstOrDefault method. this is causing the error to stop

    MSDNStudent Knows not much!

    Friday, February 17, 2012 11:18 AM