views:

177

answers:

3

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?

+5  A: 

Where filters, Select maps. Two totally different things.

helium
That doesn't actually answer the question.
Joey
@Johannes: the question asserts something that is wrong. This corrects taht aeertions, essentially marking the question as invalid. Yes it should probably be a comment, but isn't a totally invalid answer.
ck
@Johannes: Doesn't it? The difference is that they do different things, so obviously the better one to use is the one that actually does what you want.
Guffa
+2  A: 

Compare how the background code in theory would work:

// Where
foreach(var x in items)
{
    if (x.PropertyToFilterOn == filterValue)
        yield return x;
}

// Select
foreach (var x in items)
{
    yield return selector(x);
}

So mind you, the performance difference is based on the complexity of the given selector delegate. But as others have said, they serve different purposes.

Claus Jørgensen
+8  A: 

Where and Select certainly do not achieve the same thing.

Where filters the enumerable based on a predicate. The result of calling Where on IEnumerable<T> is IEnumerable<T>.

Select is 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

Winston Smith