简体   繁体   中英

Linq order by ascending sort by descending

Sorry for title, but i didn't know how to write it better. I will try in post.

When I am trying to get values from database using linq with orderby something strange happens. Let's look on 4 queries:

//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();

We got 2 ConcurrentBags<int> and 2 List<int> . What I was expecting from this is that 1 and 3 will be the same and also 2 and 4 will be the same. Check what values i got:

linq查询

Ascending sort for ConcurrentBag<int> is in fact descending. On Microsoft site we can read, that ConcurrentBag is good when sorting does not matters, but as we can see in bagDesc , sorting is kept. To show, that I don't have any strange things in database I also make two List<int> where sorting is kept as it should be.

Executing select * from produkt in my database gives me values sorted like listAsc and bagDesc .

Database is mssql 2014 and numerProduktu is primary key in this table.

Do anybody know what happened there?

See 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.

So they are getting added in reverse order. However, order is not meant to be reliably consistent in ConcurrentBag , so it's not guaranteed to always behave that way, especially if accessed by multiple threads.

If you care about maintaining the original order of entry, then you probably want a ConcurrentQueue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM