titol
titol

Reputation: 1149

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 queries

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?

Upvotes: 0

Views: 1768

Answers (1)

mellamokb
mellamokb

Reputation: 56769

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.

Upvotes: 2

Related Questions