Search code examples
c#string-search

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.


Solution

  • 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();