It may be tempting to say Split - but this has to do with creating an array and many separate lines. IMO, the best way here is to search for the first underscore and take a substring:
string b = s.Substring(0, s.IndexOf('_'));
(edit)
If you are doing this lot, you can add some extension methods:
public static string SubstringBefore(this string s, char value) { if(string.IsNullOrEmpty(s)) return s; int i = s.IndexOf(value); return i > 0 ? s.Substring(0,i) : s; } public static string SubstringAfter(this string s, char value) { if (string.IsNullOrEmpty(s)) return s; int i = s.IndexOf(value); return i >= 0 ? s.Substring(i + 1) : s; }
then
string s = "a_b_c"; string b = s.SubstringBefore('_'), c = s.SubstringAfter('_');
source share