gpt4 book ai didi

c# - Linq Order by List 给定的 ID

转载 作者:太空狗 更新时间:2023-10-29 18:22:44 24 4
gpt4 key购买 nike

我正在尝试对 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 以列表 [int] 中 npostIDs 存在的顺序返回结果?

最佳答案

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;

这将在没有 orderby 子句的情况下维护 npostIDs 的顺序。如果 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;

关于c# - Linq Order by List<int> 给定的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com