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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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".
@Morawski - order by C.KeyAsString.Length, c.KeyAsString
@Aducci @Morawski: KeyAsString must not have leading zeros though ("2" would be before "01") and no negative numbers ("0" would be before "-1").
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; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.