3

I have a datatable select like:

productData.Select("Name = 'AAA BBB # CCC'");

I know the entry is there, it just doesn't work because of the # character. I have tried escaping with [] like:

productData.Select("Name = 'AAA BBB [#] CCC'");

but it still doesn't work. I know for single quotes I double them so ' becomes ''. But what other characters do I need to be concerned with and how to get this case to work.

m3ntat
  • 3,635
  • 11
  • 38
  • 50

2 Answers2

3

Do you absolutely have to use DataTables like this? I've always been incredibly nervous of the text-based querying in DataTable for precisely this reason.

If at all possible, I suggest you start using LINQ. You can do that with DataTable already, e.g.

var query = products.AsEnumerable()
                    .Where(row => row.Field<string>("Name") == "AAA BBB # CCC");

That way you don't need to worry about escaping etc. If you use a strongly-typed dataset it becomes even simpler, as you can refer to properties directly instead of using string names.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I don't have strongly typed dataset. Wouldn't converting to Enumerable involve loop through all rows (internally) at least once just for the sake of conversion? As you have suggested this, there are less chances of it having performance penalty. Otherwise you wouldn't have suggested it. But I'm sure your answer will add something to my knowledge. – IsmailS Dec 27 '10 at 04:57
  • @Ismail: It doesn't have to convert anything - this is just returning an `IEnumerable`, and the DataTable already contains rows. – Jon Skeet Dec 27 '10 at 09:15
  • Thanks very much for your time and reply. I looked at constructor of `EnumerableRowCollection` (the one taking input as DataTable) because ultimately gets called on calling `.AsEnumerable()` on `DataTable` instance. And I found that it calls `DataTable.Rows.Cast()` which returns `IEnumerable`. So calling `products.AsEnumerable()` is as good as calling `products.Rows.Cast()`. I understood it now. Thanks again. – IsmailS Dec 29 '10 at 07:41
2

Have you tried something like this?

productData.Select(@"Name = 'AAA BBB # CCC'");
Jonathan
  • 11,809
  • 5
  • 57
  • 91