开发者

Taking item from string array that *might* be there

I have a strin开发者_JAVA百科g array, and it may contain an element with the text "mytext" within the string. eg:

mystringarray
{
    [0] => "hello world";
    [1] => "some of mytext";
}

I also have an array that doesn't have the mytext text in it.

mystringarray
{
    [0] => "hello world";
    [1] => "some of notmy";
}

My problem is when I use:

string mytextdata = mystringarray.Single<string>(t => t.Contains("mytext")).ToString();

I get an exception for the second array as it can't find an element that matches the expression.

Is there a quick way I can edit this one line to not throw an exception if it finds nothing, and instead just ignore? I have a lot of these lines and I don't want to have to wrap each in an if statement.

Apologies if question isn't clear.


string mytextdata = mystringarray.SingleOrDefault<string>(t => t.Contains("mytext"));

This will return null if nothing is found, otherwise it will return a string, so you don't need the ToString(). http://msdn.microsoft.com/en-us/library/bb342451.aspx


Maybe you can use the FirstOrDefault() method. Well - I just realized that there is a SingleOrDefault(), too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜