Why are the names NOT being printed in this given example?
customer.Select() method really NOT printing the data. Is it really NOT executing the Func<> inside the Select() method OR something different is happening here??
Code:
public static void Main()
{
var customers = new List<Customer>()
{
new Customer() { Name = "Bill" },
new Customer() { Name = "Steve" }
};
customers.Select(
c =>
{
Console.WriteLine("Name is {0}" + c.Name);
return 0;
});
Console.Read();
}
Would anybody please do let me know why it is NOT executing OR printing?
Select does not do anything unless you enumerate over the results.
As mentioned in the comment below, this is called deferred execution (thanks @BCdotNet)
You are probably looking for ForEach instead of Select:
customers.ForEach(
c =>
{
Console.WriteLine("Name is {0}" + c.Name);
});
Select is a "projection", it takes a collection as input, and produces a new collection that when enumerated over will call the specified delegate on each element of the input collection, and the result from each such delegate call is the elements of the output collection.
Since you only said "When you later enumerate over this, this is what you should do", and then never enumerated over it, nothing happened.
Select is thus more a "recipe" of how to take one collection and create another. Until you execute the recipe (enumerating over it), the recipe is just that, a recipe.
Having said all that, unless you actually need it to use Select, this is what you should do:
foreach (var c in customers)
Console.WriteLine("Name is {0}" + c.Name);
On the other hand, if you really need it to use Select, you can use the following ways to enumerate over it:
Call one of the many methods that will "force enumeration to do its job", in order of (my opinionated) applicability:
Example:
customers.Select(
c =>
{
Console.WriteLine("Name is {0}" + c.Name);
return 0;
}).LastOrDefault();
Just plain enumerate over it:
foreach (var dummy in customers.Select(
c =>
{
Console.WriteLine("Name is {0}" + c.Name);
return 0;
}))
{ } // do nothing here, empty loop body
Lastly, you're using Console.WriteLine incorrectly, you've added a parameter, but then use string concatenation to build the resulting string, meaning you will see this:
Name is {0}Bill
Name is {0}Steve
Instead, here's my final advice:
foreach (var c in customers)
Console.WriteLine("Name is " + c.Name);
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