How do I get the substring up to the first blank in C#?

100 views Asked by At

I have the following C# linqToDb query:

var instruments = (from res in _db.Instrument.Instruments.WithNoLock()
  where Sql.Like(ticker, res.Value.Substring(0, 3))
  select new
  ... etc ...

This clearly will do a comparison of ticker to the first 3 characters of res.Value. But instead I want to do the comparison to res.Value up to the first empty space, excluding that empty space. So for instance

"VVR" and "VVR UT" would match.

I have made various attempts but have failed. How can this be done?

4

There are 4 answers

3
TomTom On

This is a trivial programming exercise.

  • Find the first character that you like as separator.
  • Use substring - if you run on an outdated version of .NET. Since some version there are better ways than creating YET ANOTHER STRING.

Alternative - definitely less efficient as it DEFINITLY makes another string:

  • Use a regex.

Not a specialist here - if I have to write a regex, I have an AI write it and the test cases.

If your problem is #1, you definitely should do some basic string manipulation exercises.

2
lvbartow On

I think you could try this :

res.Value.Substring(res.Value.IndexOf(' '));
0
TomTom On

Another answer from another angle.

I think you have it backward.

If I read your code right, you look for anything where res.value.substring starts with the ticker.

Do it like that.

where res.value.StartsWith(ticker)

Then filter the results again - for anything that is a false hit, i.e.

AAA as ticker and instrument is AAAAB - that should be a small list.

ALTERNATIVELY:

where (res.value == ticker || res.Value.StartsWith(ticker + ' '))

Both approachs avoid the dynamic substring in the SQL query.

0
Scott On

Thanks, everyone. At first, I thought my issue was with linqToDb somehow, and I am not that familiar with linqToDb. But in fact, it was my misunderstanding of the IndexOf function. This fixed it:

where Sql.Like(ticker, res.Value.Substring(0, res.Value.IndexOf(' ') == -1) ? res.Value.Length : res.Value.IndexOf(' ')))