Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable Select

Tags:

c#

linq

Can someone explain why the following line of C# doesn't behave the same as the following foeach block?

string [] strs = {"asdf", "asd2", "asdf2"};
strs.Select(str => doSomething(str));


foreach(string str in strs){
  doSomething(str);
}

I put a breakpoint inside of doSomething() and it doesn't fire in the Select but it does with the foreach.

TIA

like image 822
dharga Avatar asked Nov 02 '11 19:11

dharga


People also ask

What is 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. A query expression must terminate with either a select clause or a group clause.

How does Linq select work?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.

What is IEnumerable?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

What is select method?

select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.


2 Answers

This is because LINQ queries are deferred. The lambda passed to the Select method is actually executed when you access the result.

Try:

string [] strs = {"asdf", "asd2", "asdf2"};
var result = strs.Select(str => doSomething(str));

foreach(var item in result) {
}
like image 70
Jakub Konecki Avatar answered Oct 29 '22 04:10

Jakub Konecki


The Linq query won't be processed until you convert it to an Enumarable using ToList(), ToArray(), etc.

And by the way the equivalent to your foreach statement is something like this:

strs.ForEach(doSomething);

strs.ToList().ForEach(doSomething);

or

Array.ForEach(strs, doSomething);
like image 31
fardjad Avatar answered Oct 29 '22 04:10

fardjad