I want to use a List as a queue. This is because List is more flexible when getting/inserting data.
My question is when I use Linq operations (DistinctBy, Take) as shown below, do I still get the elements in order they have been added into the list?
private List<IMessage> _queue = new List<IMessage>(); // add many _queue.Add(tagMessage); toConsume = _queue .Where(t => !_snLockList.Contains(t.Id)) .DistinctBy(t => t.Id) .Take(freeTasks).ToList();
Where,DistinctBy,TakeandToList, whether they preserve the order of thesourcesequence or not. It doesn't matter if thesourceis a list, a queue, or whatever other collection..Add()or.AddRange(), the added elements (less those that are later removed) will remain in the order added. If you insert any elements at a specific index using.Insert()or.InsertRange(), they will remain in the same position relative to the elements before and after. Be aware thatList<>is implemented using an array under the covers, so insert and remove operations at other than the end of the list can be costly, as it involves moving elements around in the array.order byor askipthe LINQ will take the distinct items where they're not in the _snLockList list. I don't understand why you wouldn't just Console/Debug.Writeline() and see for yourself testing a few scenarios?IEnumerable<T>the results will depend on the implementation of the relevant enumerator. In practice, that will almost always lead to items output in the same order as they are input unless the operation specifically requires re/disordering. That said, unless it is specifically documented, this is just a result of convenience rather than necessity and there's no guarantee that that won't change in future. Again, though, it's unlikely to ever change in practice. That said, if you specifically require an order then you should implement that yourself.