I’m investigating performance on an operation. I’m iterating a subset of items from a collection. I filter this collection using a Linq query. It basically looks like this:
var filteredItems = items.Where(x => x.PropertyToFilterOn == filterValue);
foreach (var filteredItem in filteredItems)
{
// do something to the filtered item
}
If I use Select instead of Where I achieve the same thing. Which is better to use and what is the difference?
Where and Select certainly do not achieve the same thing.
Wherefilters the enumerable based on a predicate. The result of calling Where onIEnumerable<T>isIEnumerable<T>.Selectis a projection – it allows you to map the enumerable, for example to select only a subset of the properties of the enumerated type, or construct a different object entirely based upon values of the enumerated type.Both where and select are at least O(n) – since each item in the enumeration will have to be visited to perform the projection or the filter.
The following document on the Standard Query Operators is a great reference.
http://download.microsoft.com/download/5/8/6/5868081c-68aa-40de-9a45-a3803d8134b8/standard_query_operators.doc