c#


Is it better to do ToList() before ToDictionary?


Is it worth to do the ToList() before doing the GroupBy() and ToDictionary() twice as in example below. Does the ToList() may maximize the performance when creating the dictionary? Without ToList() Resharper is yelling about possible multiple enumeration.
public void SomeMethod(IEnumerable<oldItem> oldItems)
{
var collection = oldItems.Select(i => new item()).ToList();
var dict1 = collection.ToDictionary(i => i.Key);
var dict2 = collection
.GroupBy(i => i.FieldA)
.ToDictionary(g => g.Key, g => new Flags(g.ToArray));
}
Is it better to do ToList before ToDictionary?
No, Enumerable.ToDictionary enumerates all items anyway so there is no benefit. The opposite is true, you need to fill another collection in a loop for no reason
Is it better to do ToList() before ToDictionary if i need multiple dictionaries?
Probably. It depends on the type of the sequence. It could be a database query that takes ages to execute. Without ToList you will execute it multiple times. But it could also be a collection or very cheap query. Resharper wants you to think about it.
There's another subtle difference which has nothing to do with performance. If you don't store the sequence in a collection(f.e with ToList) you could be in a deferred execution context(f.e. if oldItems is a database query). That means whenever you execute this query you will get the current result which could be different to the previous execution's result. That might be desired, you just have to keep that in mind.
Resharper warns you that the next item of the IEnumerable may be consumed twice when you intend only once. Putting the items in a list consumes the IEnumerable into a list. You can enumerate over a list as many times you want, where IEnumerable will yield the next item. collection may be consumed by the first usages, therefore the behaviour may be unexpected for the second use.
Without the ToList your collection is a SelectEnumerator around the oldItems, which will be enumerated twice for both dict1 and dict2.
This means that i => new item() will be called twice for each elements of oldItems.
I would state it simply - do not enumerate IEnumerable multiple times. Just do not do that. If you need to iterate over multiple times, you can define IList/IReadOnlyList interface. Btw. you can construct the second dictionary from values of the first in this case.
In answer to your question title, no there is no need to do that and if anything, the overhead of converting to a List will degrade performance rather than improving it. These extensions methods are already heavily optimized to give you the best performance. If there was an optimization as simple as that, then API devs behind it would have already took advantage of it.
On the other hand, there might be a cost associated with iterating through your Enumerable collection more than once so there might be some benefits in using ToList() if you intend reusing the collection more than once.

Related Links

app crashing on loading thumbnails from media library
how to receive messages in console application from GSM modem using data received handler
Html.ValidationmMessage does not show message error on client of WCF service
Using radio buttons in a calculator
Converting some classic ASP 3.0 code into C# language and ASP.NET
How to style a particular Column Header
Accurately load WinForm every time it gets focus or gets created
Selfmade Linked List extremely slow
Detecting if an exception is a Corrupted State Exception
Deadlock while writing to Process.StandardInput
Double dependency property adds precision when used with float
Weird behaviour when uploading multiple files using AngularJS
Too many exceptions for the circuit breaker?
How to I get ASP.NET Page Name
Robust Parsing xml using XmlDocument in c#
nHibernate returns double the number of records

Categories

HOME
airflow
logging
internet-explorer
optimization
popover
blob
opc-ua
grid
ms-access-2010
browser-cache
psexec
promotions
ejb-3.0
chef-recipe
eclipse-orion
swift3.1
bookmarklet
summernote
custom-component
formulas
beaker-notebook
matlab-gui
large-files
windows-10-mobile
bytebuffer
arp
spring-oauth2
ilog
odp.net
wunderground
minitest
asp.net-webhooks
kdevelop
libconfig
area
cowboy
delphi-xe
redbean
web-technologies
pexpect
grails-2.0
cakephp-3.2
codepen
jsfl
emacs24
noise
aws-rds
aot
timex
qudpsocket
mongodb-3.3
universe
cosign-api
queuing
jde
nd4j
custom-build-step
wordpress-plugin
tvp
event-tracking
windows-kernel
vanilla-forums
uinavigationitem
avrcp
android-networking
glog
fileinputstream
teamwork
esb-toolkit-2.1
radgrid
jsonschema2pojo
unityvs
livescript
msdropdown
isl
winrun4j
node-mongodb-native
code-complete
ardor3d
forward-declaration
dynamic-expresso
coinbase-php
reference-manual
qt5.1
sup
win-prolog
jqueryi-ui-buttonset
fileoutputstream
flexbuilder
method-call
nbehave
quazip
norton
cinder
google-local-search
datadude

Resources

Encrypt Message