Scorpion
Scorpion

Reputation: 23

Check if substring of a string exists in datatable

I have a DataTable like this:

  column1    column2
----------- ----------
1  abc d      Alpha
2  ab         Gamma
3  abc de     Harry
4  xyz        Peter

I want to check if a substring of a string exists in the datatable.

e.g. If the string I am looking for is "abc defg", record 3 should be returned (although record 1 is also a match, record 3 has more common characters in sequence).

I am not able to find any way to search as described above. any help, guidance would be much appreciated.

Upvotes: 2

Views: 541

Answers (1)

Jesse G
Jesse G

Reputation: 36

This would be a two-step process.

  1. Filter the table for rows that match. This can be done with the string.Contains method. In LINQ, this would look something like:
const string myText = "abc defg";
IEnumerable<Row> matches = MyTable.Where(row => myText.Contains(row.Column1));
  1. Select the longest match. In LINQ, this might look something like this.
Row longestMatch = matches.OrderByDescending<Row, int>(row => row.Column1.Length).First();

Upvotes: 2

Related Questions