How can I order in descending order and then take some elements using linq?

I have the following C # LINQ code:

List<myProductList> qMain = ( from m in db.ProductsList.OrderByDescending (it => it.GroupCode == 1 || it.L1 == 1) where m.GoodCode == 1 || m.L1 == 1 select new myProductList { StackAmount = m.StackAmount, GoodCode = m.GoodCode, PrivateCodeForSort = m.PrivateCodeForSort, GoodMainCode = m.GoodMainCode, MaxSellPrice = m.MaxSellPrice, SellPrice5 = m.SellPrice5, SellPriceType = m.SellPriceType, GoodExplain1 = m.GoodExplain1, Writer = m.Writer, DragoMan = m.DragoMan, GoodName = m.GoodName, Printing = m.Printing, CoverType = m.CoverType, PrintYear = m.PrintYear, PrintPeriod = m.PrintPeriod, Creation = m.CreationDate }).Take(50).ToList(); 

I have a serious problem, the ProductList table is very large and I donโ€™t want to transfer all rows from my database server, so I solve this problem by taking 50 rows that I need, but the problem is that I want to order in descending order first of all, then take 50 lines, but this code will first take 50 lines in ascending order, and then sort by separating only those 50 lines that have already been wrapped and sorted. how can i fix this?

+4
source share
2 answers

No, the code you provided is:

  • Orders results
  • Filters Results
  • Sets the results
  • Limits results to 50

... in that order.

On the other hand, this is a bit of an odd call to OrderByDescending to begin with. If you want a different order to be applied, you could easily do this too - for example:

  from m in db.ProductsList orderby (it.GroupCode == 1 || it.L1 == 1) descending, it.SellPrice5 descending where m.GoodCode == 1 || m.L1 == 1 select new myProductList ... // code as before 
+3
source

Something like that:

 List<myProductList> qMain = (             from m in db.ProductsList.OrderByDescending(it => it.GroupCode == 1 || it.L1 == 1)             where m.GoodCode == 1 || m.L1 == 1                                                           select new myProductList             {               StackAmount = m.StackAmount,               GoodCode = m.GoodCode,               PrivateCodeForSort = m.PrivateCodeForSort,               GoodMainCode = m.GoodMainCode,               MaxSellPrice = m.MaxSellPrice,               SellPrice5 = m.SellPrice5,               SellPriceType = m.SellPriceType,               GoodExplain1 = m.GoodExplain1,               Writer = m.Writer,               DragoMan = m.DragoMan,               GoodName = m.GoodName,               Printing = m.Printing,               CoverType = m.CoverType,               PrintYear = m.PrintYear,               PrintPeriod = m.PrintPeriod,               Creation = m.CreationDate             }).OrderByDescending(m=>m.GoodName).Take(50).ToList(); 

It will not bring the entire data set; You can look at the generated SQL query for confirmation.

0
source

Source: https://habr.com/ru/post/1392308/


All Articles