Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible purpose of LINQ select( x => x )

Tags:

c#

linq

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?

like image 430
seangwright Avatar asked Mar 31 '13 17:03

seangwright


People also ask

What is the use of Select in LINQ?

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.

What is the use of Select in C#?

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.

What does LINQ Select Return?

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.

What is Select and SelectMany in LINQ?

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.


2 Answers

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

  • MSDN - Enumerable.Select
  • MSDN - Enumerable.Where
like image 167
Daniel Imms Avatar answered Nov 02 '22 21:11

Daniel Imms


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.

like image 40
Reed Copsey Avatar answered Nov 02 '22 19:11

Reed Copsey