2

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.

Scorpion
  • 23
  • 4
  • 1
    Please read the [how-to-ask page](https://stackoverflow.com/help/how-to-ask) and read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) to improve your question and help us to understand your problem. – Trevor Mar 25 '21 at 20:14
  • From an XML file. In the XML file also the quotes are spread across multiple tags. – Scorpion Mar 25 '21 at 20:14
  • Have you looked into using a `Regular Expression`? – Brian Mar 25 '21 at 20:48
  • @Brian , yes. But maybe I am not verse enough in regex to back search as needed in this scenario. I.e finding a substring of the search string in the data table. – Scorpion Mar 25 '21 at 21:09
  • Use `string.Contains` method and `string.Length` property. This is enough to solve your problem. – Alexander Petrov Mar 25 '21 at 21:13

1 Answers1

2

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();
Jesse G
  • 36
  • 3