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
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.
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.
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.
select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
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) {
}
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);
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