So I’ve been using LINQ for a while, and I have a question.
I have a collection of objects. They fall into two categories based on their property values. I need to set a different property one way for one group, and one way for the other:
foreach(MyItem currentItem in myItemCollection) { if (currentItem.myProp == 'CATEGORY_ONE') { currentItem.value = 1; } else if (currentItem.myProp == 'CATEGORY_TWO') { currentItem.value = 2; } }
Alternately, I could do something like:
myItemCollection.Where(currentItem=>currentItem.myProp == 'CATEGORY_ONE').ForEach(item=>item.value = 1); myItemCollection.Where(currentItem=>currentItem.myProp == 'CATEGORY_TWO').ForEach(item=>item.value = 2);
I would think the first one is faster, but figured it couldn’t hurt to check.
Iterating through the collection only once (and not calling any delegates, and not using as many iterators) is likely to be slightly faster, but I very much doubt that it’ll be significant.
Write the most readable code which does the job, and only worry about performance at the micro level (i.e. where it’s easy to change) when it’s a problem.
I think the first piece of code is more readable in this case. Less LINQy, but more readable.