I have this method which return an array of string :
private static string[] ReturnsStringArray()
{
return new string[]
{
"The path of the ",
"righteous man is beset on all sides",
"by the inequities of the selfish and",
"the tyranny of evil men. Blessed is",
"he who, in the name of charity and",
"good will, shepherds the weak through",
"the valley of darkness, for he is",
"truly his brother's keeper and the",
"finder of lost children. And I will ",
"strike down upon thee with great",
"vengeance and furious anger those",
"who attempt to poison and destroy my",
"brothers. And you will know my name",
"is the Lord when I lay my vengeance",
"upon you"
};
}
}
I want to write a method which use this method. As this method returns an array and not a IEnumerable, is there the same result to write this :
private static IEnumerable<string> ParseStringArray()
{
return ReturnsStringArray()
.Where(s => s.StartsWith("r"))
.Select(c => c.ToUpper());
}
and this :
private static List<string> ParseStringArray()
{
return ReturnsStringArray()
.Where(s => s.StartsWith("r"))
.Select(c => c.ToUpper())
.ToList(); // return a list instead of an IEnumerable.
}
Thank you.
EDIT
My question is : Is there any interest or benefits that the method ParseStringArray() returns an IEnumerable instead of a List because of this method calls ReturnsStringArray that returns an array of string and not a IEnumerable
When you return a
List, you are saying that “all processing has been done, and the List contains the results”.However, when you return an
IEnumerable, you are saying that “processing might still need to be done”.In your example, when you return an
IEnumerable, the.Whereand.Selecthave NOT bee processed yet. This is known as “deferred execution”.If the user uses the result 3 times, then the
.Whereand.Selectwill execute 3 times. There are a good number of tricky issues that can come from this.I recommend using a
Listas often as possible when returning values from a method. In addition to the additional functionality you’ll get from aList, .NET has many optimizations that require aList, debugging support is better, and there’s a reduced chance of unintended side effects!