2015-06-08 68 views
0

我想將此sql語句轉換爲Linq格式,但沒有成功。我不想顯示所有數據,而是想顯示每個類別的10個項目。任何幫助都會很棒。如何將SQL轉換爲Linq

select * 
from (
    select *, 
      row_number() over(partition by T.category order by T.id desc) as rn 
from clothes as T 
) as T 
where T.rn <= 10; 

我在linq的嘗試在下面;

var query= from (subquery) as DB in dataContext.table where DB.rn <=10; 
       select DB; 
var subquery = row_number() over(partition by DB.id order by DB.category desc) as rn from DB in dataContext.table as DB 
        select DB; 
+0

可能重複【行\ _number在Linq中(用xxx分區)?](http://stackoverflow.com/問題/ 9980568/row-number-over-partition-by-xxx-in-linq) – Chris

回答

1

使用GroupByTakeSelectMany應該做的伎倆

var result = dataContext.table.GroupBy(m => m.category) 
      .SelectMany(g => g.OrderByDescending(x => x.Id).Take(10)); 
+0

嘿拉斐爾,這很奏效。非常感謝! – georgieboy