I have a dictionary which I need to keep updated with incoming data, after parsing the incoming data I have to check if there are any entries in the dictionary which are not present in the incoming data (incoming data when parsed is a list and I need to map it with the dictionary entries).
To avoid multiple loops to removed the entries, I ran a decrementing for loop for dictionary count, then I fetch the dictionary key of the index using ElementAt, then check if the entry is present in the incoming data if not then I remove that entry from the list. I did this because running the foreach loop on the dictionary keys and removing from it will raise and exception as the dictionary keys collection would be modified.
I wanted to understand that doing this will there be any impact on execution time. I want to understand what is the order of ElementAt operation.
ElementAtis useful if you need to provide indexing semantics and cannot guarantee that indexing semantics will be available in the underlying enumeration. It does use O(1) indexing when the enumeration acted upon is anIList<T>(which includes List and arrays), but otherwise is O(n)*, which makes it being used in a sequence over everything go from the O(n) operation it would be with a list to O(n * n).If however you got a copy of the keys with
dict.Keys.ToList()then you could safelyforeachthrough that, as it won’t be changed by changes to your dictionary.What isn’t clear is why you don’t just replace the old dictionary with the new one, which would be considerably faster again (simple reference assignment).
*Update: In the .NET Core version of linq there are a greater range of cases where
ElementAt()is O(1) such as the results of aSelect()done on anIList<T>. AlsoOrderBy(…).ElementAt(…)is now O(n) rather than O(n log n) as the combined sequence is turned into a quick-select rather than a quicksort followed by an iteration.