简体   繁体   中英

How do I select the top ten scores in a database table full of scores using linq in C#

I'm new to Linq and database programming in general, I could really use some help.

I have tried using

var TopTen =  from t in datacontext.Scores.Take(10)
              orderby t.LifetimeScore descending
              select t;

but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.

Thanks, any help is appreciated

You have to take 10 from the result, not before:

var TopTen = (from t in datacontext.Scores 
              orderby t.LifetimeScore descending 
              select t).Take(10);
var TopTen =  datacontext.Scores.OrderByDescending(t => LifetimeScore ).Take(10)

I'm new to LINQ myself but here's what I think should work:

var TopTen =  (from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t).Take(10);
var TopTen =  from t in datacontext.Scores
              orderby t.LifetimeScore descending
              select t;
TopTen = TopTen.Take(10).ToArray();

Last statement will make sure the query is executed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM