title: Issues Doing a String Comparison in LINQ
body: <p>I'm having trouble getting LINQ to translate something into the query I need.  In T-SQL, we do a &lt;= and >= comparison on three columns that are CHAR(6) columns.  LINQ will not allow me to do this since</p>
  
  <blockquote>
    <p>Operator '&lt;=' cannot be applied to
    operands of type 'string' to 'string'.</p>
  </blockquote>
  
  <p>I have the following T-SQL query..</p>
  
  <pre><code>SELECT * 
  FROM [ZIPMASTER] zm
  WHERE zm.CORP = 12 
  AND '85546 ' BETWEEN zm.ZIPBEG AND zm.ZIPEND
  </code></pre>
  
  <p>The above is not very LINQ freindly, since there is no support for <code>BETWEEN</code>.  Thus, I have simplified to the following:</p>
  
  <pre><code>SELECT *
  FROM [ZIPMASTER] zm
  WHERE zm.CORP = 12
  AND zm.ZIPBEG &lt;= '85546 '
  AND zm.ZIPEND &gt;= '85546 '
  </code></pre>
  
  <p>Which I have used to create the following LINQ query:</p>
  
  <pre><code>var zipLinqQuery =
      from z in db.ZIPMASTERs
      where z.CORP == 12
      &amp;&amp; z.ZIPBEG &lt;= "85546 "
      &amp;&amp; z.ZIPEND &gt;= "85546 "
      select z;
  List&lt;ZIPMASTER&gt; zips = zipLinqQuery.ToList&lt;ZIPMASTER&gt;();
  </code></pre>
  
  <p>C# - LINQ is not liking this query too much.  I tried converting to ints and then comparing, however, in some cases the zip code might contain a letter.  For example, the following expression would evaluate to true in T-SQL:</p>
  
  <pre><code>WHERE '85546B' BETWEEN '85546A' AND '85546D'
  </code></pre>
  
  <p>I don't know exactly why it works in T-SQL, but my guess is that it compares each character in the array individually by converting it to a numerical ASCII value.</p>
  
  <p>Anyway, any help you all can provide is greatly appreciated.  Thanks in advance.</p>
  
  <p>CJAM</p>
  
  <p><b>Solution (posted by Jon Skeet):</b></p>
  
  <p>It appears that string.CompareTo() does in fact generate the needed T-SQL.  Examples below:</p>
  
  <pre><code>var zipLinqQuery =
      from z in db.ZIPMASTERs
      where z.CORP == listItem.CORP
      &amp;&amp; z.ZIPBEG.CompareTo(listItem.ZIPCODE) &lt;= 0
      &amp;&amp; z.ZIPEND.CompareTo(listItem.ZIPCODE) &gt;= 0
      select z;
  </code></pre>
  
  <p>Generates the following T-SQL:</p>
  
  <pre><code>DECLARE @p0 INT, @p1 CHAR(6), @p2 CHAR(6)
  SET @p0 = 12
  SET @p1 = '85546 '
  SET @p2 = '85546 '
  
  SELECT [t0].[CORP], [t0].[ZIPEND], [t0].[ZIPBEG], [t0].[CITY], [t0].[STATE], [t0].[CYCLE]
  FROM [dbo].[ZIPMASTER] AS [t0]
  WHERE ([t0].[CORP] = @p0) AND ([t0].[ZIPBEG] &lt;= @p1) AND ([t0].[ZIPEND] &gt;= @p2)
  </code></pre>