razorumbraco8

Check If Value is Not Null before I get the ID


Here is my Code:

var item = (ElementPricingItem)block.Content;
var priceBlock = item.PricingPrice.FirstOrDefault(p => ((ElementPriceSize)p.Content).TeamSize.Id == size.Id);
var price = (ElementPriceSize)priceBlock.Content;
if (item.PricingPrice != null && price.Price != null && price.TeamSize != null)
    {
        <div class="col-lg-3 col-md-6 col-12 mt-4 pt-2">
            <div class="card pricing-rates business-rate shadow @Html.If(item.BgCardColor == true, "bg-light") border-0 rounded">
                <div class="card-body js-rte-bullet-point">
                    <h2 class="title text-uppercase mb-4">@item.PricingType</h2>
                    <div class="d-flex mb-4">
                        <span class="price h1 mb-0">@price.Price</span>
                            <span class="h4 align-self-end">CHF</span>
                                <span class="h4 align-self-end">/year</span>
                    </div>
        <p>@Html.Raw(item.PricingBenefits)</p>
        @if (item.PricingCta != null)
        {
           <a href="@item.PricingCta.Url" class="btn btn-primary mt-4">@item.PricingCta.Name</a>
        }
        </div>
        </div>
        </div>
}

I need to check if there is an price.TeamSize before i get the ID in the var priceBlock. The problem is my variable price is useing the priceBlock. So I can't check the price.TeamSize before the priceBlock.

Does anyone knows how to fix this?


Solution

  • Some one answerd the question, but deleted his answer afterawrds, eventhough it worked for me.

    I had to change following:

    Because i wasn't able to check if prices.TeamSize was null before i changed the priceBlock variable to this:

    From
    
    var priceBlock = item.PricingPrice.FirstOrDefault(p => ((ElementPriceSize)p.Content).TeamSize.Id == size.Id);
    
    to this: 
    
    var priceBlock = item.PricingPrice.FirstOrDefault(p => ((ElementPriceSize)p.Content).TeamSize?.Id == size.Id);
    

    The "?" checks if the TeamSize is null. Also I had to change the IF to this:

    From:
    var price = (ElementPriceSize)priceBlock.Content;
    if (item.PricingPrice != null && price.Price != null && price.TeamSize != null)
    {
    //kjsdhf
    }
    to this: 
    if (priceBlock != null)
    {
      var price = (ElementPriceSize)priceBlock.Content;
    }
    

    Thank you whoever answerd, It worked for me lol:)