开发者

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜