C# – Issues Doing a String Comparison in LINQ

clinqnetsql

I'm having trouble getting LINQ to translate something into the query I need. In T-SQL, we do a <= and >= comparison on three columns that are CHAR(6) columns. LINQ will not allow me to do this since

Operator '<=' cannot be applied to
operands of type 'string' to 'string'.

I have the following T-SQL query..

SELECT * 
FROM [ZIPMASTER] zm
WHERE zm.CORP = 12 
AND '85546 ' BETWEEN zm.ZIPBEG AND zm.ZIPEND

The above is not very LINQ freindly, since there is no support for BETWEEN. Thus, I have simplified to the following:

SELECT *
FROM [ZIPMASTER] zm
WHERE zm.CORP = 12
AND zm.ZIPBEG <= '85546 '
AND zm.ZIPEND >= '85546 '

Which I have used to create the following LINQ query:

var zipLinqQuery =
    from z in db.ZIPMASTERs
    where z.CORP == 12
    && z.ZIPBEG <= "85546 "
    && z.ZIPEND >= "85546 "
    select z;
List<ZIPMASTER> zips = zipLinqQuery.ToList<ZIPMASTER>();

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:

WHERE '85546B' BETWEEN '85546A' AND '85546D'

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.

Anyway, any help you all can provide is greatly appreciated. Thanks in advance.

CJAM

Solution (posted by Jon Skeet):

It appears that string.CompareTo() does in fact generate the needed T-SQL. Examples below:

var zipLinqQuery =
    from z in db.ZIPMASTERs
    where z.CORP == listItem.CORP
    && z.ZIPBEG.CompareTo(listItem.ZIPCODE) <= 0
    && z.ZIPEND.CompareTo(listItem.ZIPCODE) >= 0
    select z;

Generates the following T-SQL:

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] <= @p1) AND ([t0].[ZIPEND] >= @p2)

Best Answer

Try:

var zipLinqQuery =
    from z in db.ZIPMASTERs
    where z.CORP == 12
    && z.ZIPBEG.CompareTo("85546 ") <= 0
    && z.ZIPEND.CompareTo("85546 ") >= 0
    select z;

I don't know that String.CompareTo works in LINQ to SQL, but it's the first thing to try.

(Normally you should use a StringComparer to specify the right type of comparison, but I suspect in this case CompareTo is the better option.)