-3

I have this code to select a row from DGV.

if (row.Cells[1].Value.ToString().Equals(searchValue))
{
    row.Selected = true;
    break;
}

Is there anything like

%".$searchvalue."%

from sql to use in C#, so it would found seemingly entrances not only exactly ones?

Mincong Huang
  • 5,284
  • 8
  • 39
  • 62
Vvisions
  • 51
  • 1
  • 7
  • 1
    Possible duplicate of [How to do SQL Like % in Linq?](http://stackoverflow.com/questions/835790/how-to-do-sql-like-in-linq) – Gilad Green Jun 28 '16 at 13:07

3 Answers3

1

If you want to find out only the entrances of the string you can use StartsWith like below.

if (row.Cells[1].Value.ToString().StartsWith(searchValue))
{
    row.Selected = true;
    break;
}

If you want to find out only the endings of the string you can use EndsWith like below.

if (row.Cells[1].Value.ToString().EndsWith(searchValue))
{
    row.Selected = true;
    break;
}

You can use contains in the above cases if you are not so worried about the performance.

Venkata Dorisala
  • 4,783
  • 7
  • 49
  • 90
  • StartsWith will only look for first cahracters of first word or will it look for first characters of any word ? And what would be the performance impact if I use contains? – Vvisions Jun 28 '16 at 13:16
  • It looks for only first characters of the first word. `Contains` uses a different algorithm and it needs to compute more combinations than `StartsWith` or `EndsWith`. Hence it is used for the cases where we dont know where our required string matcher lies. If you are so sure about what you need to search and it comes up in the begining or ending then you can use these. Otherwise `Contains` is not a bad choice. – Venkata Dorisala Jun 28 '16 at 13:21
  • If you want to check first characters of every word then you need to split the string by `space` and loop through each piece to check whether it startswith `matching string` or not. – Venkata Dorisala Jun 28 '16 at 13:21
0

Use string.Contains instead of Equals

if (row.Cells[1].Value.ToString().Contains(searchValue))
{
    row.Selected = true;
    break;
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

In general case, if you want to mimic sql LIKE construction you can try regular expressions:

public static bool Like(String value, String like) {
  if (String.IsNullOrEmpty(like) || String.IsNullOrEmpty(value))
    return false; // or throw exception

  String pattern = "^" + Regex.Escape(like).Replace("%", ".*").Replace("_", ".") + "$";

  return Regex.IsMatch(value, pattern);
}

....

String source = "abcdef";
// true
bool result = Like(source, "%b_d%");

In your case

if (Like(row.Cells[1].Value.ToString(), searchValue)) { ... }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215