3

I am writing a LINQ query against the ObjectContext. What I essentially need to do in LINQ to Entities is this (I know this won't work, but I'm doing it this way to illustrate):

from c in context.Table
where key == int.Parse(c.KeyAsString)
order by int.Parse(c.KeyAsString)
select c

I wasn't sure if this was possible... anybody know of a way?

Thanks.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257

2 Answers2

3

try it the other way around. I assume "key" is a variable int so cast that to string by using ToString() and use that to compare with KeyAsString and in the order by don't use a cast:

var keyString = key.ToString();
var query = from c in context.Table
where keyString == c.KeyAsString
order by c.KeyAsString
select c

if you have trouble with the order by use a method like ToList() or ToArray() to pull the results into memory and there you'll be able to cast to int or use a custom comparer.

Juan Ayala
  • 3,388
  • 2
  • 19
  • 24
  • Sorting by string value is not going to give you the same order as sorting by numeric value - "11" will go after "1", but before "2". – Konrad Morawski Aug 15 '11 at 16:48
  • 6
    @Morawski - **order by C.KeyAsString.Length, c.KeyAsString** – Aducci Aug 15 '11 at 16:52
  • 2
    @Aducci @Morawski: `KeyAsString` must not have leading zeros though ("2" would be before "01") and no negative numbers ("0" would be before "-1"). – Slauma Aug 15 '11 at 18:30
1

This is not the cleanest looking solution, but it will work as long as all your strings are valid integers. This can be used with doubles as well

var query = from c in context.Table
            let IntOrder = context.Table.Take(1).Select(x => c.KeyAsString).Cast<int>().FirstOrDefault()
            where IntOrder == key
            orderby IntOrder
            select c; 
Aducci
  • 26,101
  • 8
  • 63
  • 67