c# - How to deal with nulls in Linq to SQL with Regex.Replace on Property -


the following portion of code larger linq query, 1 need with:

knowledgetypetext = regex.replace((from categoryversion in _context.articlecategoryversions                                    join category in _context.categories                                    on categoryversion.categoryid equals category.categoryid                                    category.parentid.hasvalue == true                                    && category.parentid.value == rootknowledgetypeid                                    && categoryversion.version == articlelatestversions.version                                    && categoryversion.articleid == articlelatestversions.articleid                                    select category).first().name, @"(\d+[\\.]?\s*)", ""), 

the short version: part of query fetch category article, doesn't necessary have have value. if have value need strip out numbering @ beginning of text.

i'm getting exceptions when category null because it's trying replace action on property name.

how add in code deal nulls? safe return empty string, i'm not sure how test , return empty string.

  • if fail on first() because sequence contains no elements replace .firstordefault().
  • if value null , fails on null reference when accessing name use .firstordefault()?.name
  • if name property null use ??:

    (/* query */).firstordefault()?.name ?? string.empty 

read more on:


in addition less readable putting inline (even more seems in object initializer). first have query , replace:

var result = (from categoryversion in _context.articlecategoryversions               join category in _context.categories               on categoryversion.categoryid equals category.categoryid               category.parentid.hasvalue &&               category.parentid.value == rootknowledgetypeid &&               categoryversion.version == articlelatestversions.version &&               categoryversion.articleid == articlelatestversions.articleid &&               select category).firstordefault()?.name ?? string.empty;  knowledgetypetext = regex.replace(result, @"(\d+[\\.]?\s*)", ""); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -