gpt4 book ai didi

c# - Linq 按升序排序 按降序排序

转载 作者:行者123 更新时间:2023-11-29 07:33:10 24 4
gpt4 key购买 nike

对不起,我的标题,但我不知道如何写得更好。我会在帖子中尝试。

当我尝试使用 linq 和 orderby 从数据库中获取值时,会发生一些奇怪的事情。让我们看一下 4 个查询:

//1
var badAsc = new ConcurrentBag<int>((from x in se.produkts orderby x.numerProduktu select x.numerProduktu));
//2
var bagDesc = new ConcurrentBag<int>((from x in se.produkts orderby x.numerProduktu descending select x.numerProduktu));
//3
var listAsc = (from x in se.produkts orderby x.numerProduktu select x.numerProduktu).ToList();
//4
var listdesc = (from x in se.produkts orderby x.numerProduktu descending select x.numerProduktu).ToList();

我们有 2 ConcurrentBags<int>和 2 List<int> 。我对此的期望是 1 和 3 相同,2 和 4 也相同。检查我得到的值:

linq queries

升序排序ConcurrentBag<int>事实上是下降的。在 Microsoft 网站上我们可以看到 ConcurrentBag当排序不重要时很好,但正如我们在 bagDesc 中看到的那样,排序被保留。为了表明我的数据库中没有任何奇怪的东西,我还制作了两个 List<int>排序保持应有的样子。

执行select * from produkt在我的数据库中给我排序的值如 listAscbagDesc .

数据库是mssql 2014numerProduktu是该表中的主键。

有人知道那里发生了什么吗?

最佳答案

参见here .

The ConcurrentBag appears to be implemented as a stack rather than a queue. That is, the last item added is the first item removed. I wouldn't count on that, though.

所以它们是以相反的顺序添加的。然而,顺序并不意味着 ConcurrentBag 中的顺序可靠一致。 ,因此不能保证始终以这种方式运行,尤其是在由多个线程访问时。

如果您关心保持原始的条目顺序,那么您可能需要 ConcurrentQueue .

关于c# - Linq 按升序排序 按降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899224/

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