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()
becausesequence contains no elements
replace.firstordefault()
. - if value
null
, fails on null reference when accessingname
use.firstordefault()?.name
if
name
propertynull
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
Post a Comment