简体   繁体   中英

How do you trim a string that might be null in Linq?

I have a string in linq which is loaded from xml, that attribute or element is optional, but I want to trim the string because the xml file can be written manually like this.

<text>Hello World</text>

or like this

<text>
    hello world
<text>

the later will create the new line characters before and afterwards which i want trimming.

I tried to do

QuestionText = (string)query.Element("text").ToString().Trim()

but that crashes the app when that element is not present.

QuestionText = query.Element("text")!=null ? query.Element("text").Value.Trim() : string.Empty;

Is it possible this in WP7?

QuestionText = ((string)query.Element("text") ?? string.Empty).Trim();

Cheers

I might be tempted to make an extension method for XElement

public static class XElementExtensions
{
  public static string TrimmedValue(this XElement elem)
  {
     if(elem == null)
        return null; // or, possibly String.Empty depending on your requirement.
     if(String.IsNullOrEmpty(elem.Value))
        return elem.Value
     return elem.Value.Trim();
  }
}

Usage then:

QuestionText = query.Element("text").TrimmedValue()

If you are ok with returning an empty string on null, How about?

QuestionText = (query.Element("text")+"").Trim()

[I use this other places to convert null strings, but of course since the question is ambiguous as to what to do with nulls/empty's this could be different than what you need]

firstly, don't cast a string to a string.

How about this...

string QuestionText = "";
if(query.Element("text") != null)
   QuestionText = query.Element("text").ToString().Trim();
QuestionText = Convert.ToString(query.Element("text")).Trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM