I'm going through some LINQ examples from a book on MVC and I'm wondering what purpose the select call below could have. Maybe it's a typo but I don't see any mention of it in the book's errata.
foreach( Product p in products
.Where( e => e.Name == productParam.Name )
.Select( e => e ) ) {
p.Price = productParam.Price;
}
I tested out two examples of this where the .Select( e => e) was included and one where it was not and the code is the same. Since Where returns the IEnumerable filtered by the predicate then when would the select call (with the specific predicate above) ever be necessary? Does it actually do anything? Could it in some weird corner case?
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
In a query expression, the select clause specifies the type of values that will be produced when the query is executed. The result is based on the evaluation of all the previous clauses and on any expressions in the select clause itself.
By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.
It would return the exact same thing as without it, an IEnumerable<T>
. It's actually doing more harm than good though as it's performing a redundant O(n) operation (looping through the whole list).
References
Does it actually do anything?
It does add overhead to the entire operation. In reality, it should be removed, as it serves no useful purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With