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
  • 7,794
  • 19
  • 28
  • 47
Eternal21
  • 3,551
  • 1
  • 42
  • 55
  • 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
  • 161,100
  • 35
  • 287
  • 281
erikkallen
  • 32,795
  • 13
  • 83
  • 117