Call method x times using linq
You can System.Linq.Enumerable
to repeat an Action multiple times.
Enumerable.Repeat<Action>(() =>
{
lstNews.Add(CollectNews);
}, 3);
This would run the Add
method on the list 3 times. Docs on Enumerable.Repeat
here.
var lstNews = Enumerable.Repeat(0, 3).Select(_ => CollectNews()).ToList();
As I understand you want to end up with a list of three News
objects. You can do something like
Enumerable.Repeat(1, 3).Select(_ => CollectNews()).ToList();
You could use any value in place of 1
in that example.
While this approach works, it's sort of abusing the idea of LINQ. In particular, you should not assume any order of executing CollectNews()
calls. While the standard Select
implementation will execute in sequence this may not always be true.