簡體   English   中英

Linq按列表排序 <int> 給出的ID

[英]Linq Order by List<int> of IDs given

我正在嘗試對linq查詢進行排序,以便按List [int]中找到的ID的順序返回結果。 這是我當前的代碼返回它們很好,但沒有排序。

IEnumerable<NPost> nposts;

List<int> npostIDs = (from tc in db.TopComs
                      where tc.Type == "Comments"
                      select tc.NPostID).ToList();

            nposts = from np in repository.NPosts
                     where npostIDs.Contains(np.NPostID)
                     select np;

我怎樣才能讓nposts以List [int]中存在npostID的順序返回結果?

IEnumerable<NPost> nposts = from np in repository.NPosts
                            let index = npostIDs.IndexOf(np.NPostID) 
                            where index >= 0
                            orderby index ascending
                            select np;

更新

根據你的錯誤,我有另一個建議。 我不是100%肯定它是否會在EF中起作用,但試一試並讓我知道。 還有另外一個我知道會有用的想法,但它不會表現得那么好。

IEnumerable<NPost> nposts = from npostID in npostIDs.AsQueryable()
                            join np in repository.NPosts
                            on npostID equals np.NPostID
                            select np;

這將保持npostIDs的順序而不使用orderby子句。 如果ObjectContext是相同的(如果不是),您實際上應該能夠在單個查詢中執行它。 但是,目前尚不清楚是否要緩存npostIDs列表,因此這可能不是一個選項。 無論如何,這里:

IEnumerable<NPost> nposts = from tc in db.TopComs
                            where tc.Type == "Comments"
                            join np in repository.NPosts
                            on tc.NPostID equals np.NPostID
                            select np;

接受的答案是正確的,我只是想提供這個答案的方法版本:

IEnumerable<NPost> nposts = repository.NPosts
                            .Where(np => npostIDs.IndexOf(np.NPostID) >= 0)
                            .OrderBy(np => npostIDs.IndexOf(np.NPostID));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM