Some say linq isn’t bad some say linq is very bad it could cause many problems… I am really confused cause if I don’t want to use foreach the first thing that comes to my mind for iterating through collections is for loops and linq (mostly dictionaries). For example is .ElementAt() very bad or not so much and better than using foreach loops ?
for (int index = 0; index < dictionary.Count; index++) {
var item = dictionary.ElementAt(index);
var itemKey = item.Key;
var itemValue = item.Value;
}
is this way of iterating dictionaries much better than foreach loop ?
linq can have performance implications, but you should follow @vexe’s advice in your other question about the evils of foreach - get your code working before you waste time on optimizations.
@deadliness iterating a dictionary using ElementAt is just as bad if not worse than using a foreach. ElementAt uses O(1) indexing when the underlying IEnumerable is an IList, otherwise O(n); and it would create the Enumerator object and iterate over it, just like foreach. So your best is to use foreach.
If you want, you could use my dictionary (well, not really a dictionary cause I’m not hashing) implementation which uses two lists, one for keys and other for values. You could iterate over the keys and values in a for loop without worrying about generating anything. You get an extra benefit of the thing being serializable with Unity’s serialization system Better Dictionary? (serializable with more functionality) - Unity Answers