0

I want to parse an SQL-like input, for example:

SEX = 'MALE' AND AGE > 20

Based on the 'sql' input I then search through my c# array of Items.

So for example above, I would search my data for all items that have their Item.Sex property set to 'MALE' and their Item.Age property is greater than 20.

This is a trivial example, and you can easily start imagining more complex scenarios. For example:

(SEX = 'MALE' AND AGE > 20) OR (SEX = 'FEMALE' AND AGE < 30)

I need to be able to support the following operators:

=
>
<
<>
() - for precedence
AND
OR

I have a feeling I'll end up having to code this myself from scratch, but don't want to re-invent the wheel. After looking into this for a bit, I did come across references to parsers/grammar etc, but am not quite sure if those fit the bill.

niton
  • 8,771
  • 21
  • 32
  • 52
Eternal21
  • 4,190
  • 2
  • 48
  • 63
  • 1
    You can use tools like ANTLR (or the C# equivalent) or a Parser-Combinator library (if there is one for C#) to make life simpler. –  Sep 20 '12 at 19:21
  • Have a look at using Expression Trees http://msdn.microsoft.com/en-us/library/bb397951.aspx – Adriaan Stander Sep 20 '12 at 19:22
  • 1
    For an ANTLR & C# demo, see: http://stackoverflow.com/questions/4396080/antlr-3-3-c-sharp-tutorials – Bart Kiers Sep 20 '12 at 19:22
  • @astander Is there a way to go from string -> Expression Tree easily? (I assumed, perhaps incorrectly, the input is text.) –  Sep 20 '12 at 19:23
  • Not that I am aware of, the other suggestions here seems good though – Adriaan Stander Sep 20 '12 at 19:24

1 Answers1

1

You will probably need to parse the input yourself, but with a parser generator such as ANTLR, it is not too much work.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
erikkallen
  • 33,800
  • 13
  • 85
  • 120