I just saw an SO question about the System.Collections.ConcurrentBag<T> class, and I’ve seen the ViewBag property of the Controller in ASP.NET MVC. In my experience, I’ve learned that it’s easier to use people’s code if you understand what exactly they were getting at in writing it. I think its pretty intuitive as to what a List<T> or a Dictionary<TKey,TValue> or a ReadOnlyCollection<T> are meant to represent. A Bag on the other hand is not so intuitive.
So, my question is: What is this Bag metaphor meant to represent, specifically with respect to the .NET framework?
ConcurrentBag<T>is a thread-safe, unordered sequence of items which can include duplicates.So compared with some other collections:
HashSet<T>but unlike aList<T>List<T>but unlike aHashSet<T>Dictionary<TKey, TValue>)Possible uses include a work queue where you don’t care about the ordering (as otherwise you’d use
ConcurrentQueue/ConcurrentStack) or a list of items where you’ll always apply a sort order after fetching the data into another “local” collection.