views:

408

answers:

2

Is there a way to perform a top (Take) linq query using percentage? The T-SQL would have been:

SELECT TOP 20 PERCENT ...

But LINQ seems to only want an int.

It seems that I would have to do a count and then a take. Any suggestions?

+2  A: 

You would have to perform the query twice, in essence. You would have to perform it once to get a count, and then again to figure out the percentage (because you will pass the number that corresponds to the count that will equal 20%).

casperOne
That's what I'm doing, and I don't like it :/ There should be a method that translates to the native SQL.
Tony Basallo
@Basallo: Unfortunately, I don't believe there is.You ^could^ extend the IQueryable implementation somehow to support your own override of Top, which would then translate it to the appropriate SQL Server command.
casperOne
@tony: One note, even though it's 2 trips, it's not as bad as it may seem. query.Count() gets executed as SELECT COUNT(), so at least it's not returning all rows, counting, then selecting all again. As the others state, stored procs and views would be another way to do this...
Daniel
@Daniel: The problem with that is that you are still executing the query twice. If you really want to do it the right way, one should override the IQueryable implementation to support a Top method (named TopPercentage, perhaps) which will perform the work.
casperOne
A: 

I don't think there's anything built into LINQ to SQL. You could do it with a stored procedure. I don't like that much, unless you happen to be using a procedure anyway, but it's probably better than doing it with two separate queries.

Craig Stuntz
A view would probably be more appropriate.
Adam Lassek