0

I'm struggling to translate the following SQL query into LINQ. The outcome column is in type (varchar) in the database and I want to cast that into float/double with LINQ.

SELECT TOP 10 CAST(Outcome AS float) AS Max_Outcomes
FROM GameState
where GameId = 1000
ORDER BY Max_Outcomes DESC

Much appreciated!

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Artavazd
  • 145
  • 4
  • 12
  • Imo the error, and your attempt would have been usefull. It's a dupe of either "SQL top linq" , "sql order by in linq", or "sql cast ef float". Note that those are not title of real question it's barely keywords used to find hundred of dupe target. Basically I think that something like this https://stackoverflow.com/questions/14939961/ , https://stackoverflow.com/questions/41828974/ – Drag and Drop Apr 07 '20 at 12:29

1 Answers1

1

Something like this:

var result = _yourDbContext.GameState
             .Where(c => c.GameId == 1000).AsEnumerable()
             .Select(c => new { Max_Outcomes = (float)c.Outcome })
             .OrderByDescending(c=> c.Max_Outcomes).Take(10).Tolist()
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • you can't do casting because entity framework will not understand it. also max_outcomes doesn't exist in this context. that's where I am having the problem. – Artavazd Apr 07 '20 at 11:47
  • @Artavazd See my updated answer. Regarding EF to understand cast, you can use `AsEnumerable()`, and for `Max_Outcomes` you can use anonymous type like my updated answer. – Salah Akbari Apr 07 '20 at 11:49
  • ah, we can do ordering after the selection. it works that way. – Artavazd Apr 07 '20 at 11:57