user1590636
user1590636

Reputation: 1194

Substring when a string contains, Linq syntax

in Linq i have somthing like

nodes.Select(td => td.InnerText.
                Replace("&", "&").
                Substring(0, td.InnerText.IndexOf("+"))).
                ToArray();

some times td.InnerText contians a + sign and sometimes it doesn't and if it doesn't i get null reference exception.

how can i apply Substring(0, td.InnerText.IndexOf("+"))) only if td.InnerText contains "+" ?

Upvotes: 1

Views: 699

Answers (2)

Ehsan
Ehsan

Reputation: 32681

you can do this

td.InnerText.Replace("&", "&").Substring(0, td.InnerText.IndexOf("+") > -1 ? td.InnerText.IndexOf("+") : 0);

Upvotes: 2

user240141
user240141

Reputation:

Try using ternary operator. This might not work properly but will give you a hint.

nodes.Select(td => td.InnerText.Replace("&", "&").Substring(0, 
    (td.InnerText.Contains("+")==true? td.InnerText.IndexOf("+"):string.Empty))).
                    ToArray();

Upvotes: 1

Related Questions