I would like to call one method 3 times Using LINQ, the method returns an object, with that object I want to add it into a List, How do i do it?
List<News> lstNews = new List<News>();
lstNews.Add(CollectNews) [x 3 times] <-- Using Linq
private static News CollectNews(){
...
}
var lstNews = Enumerable.Repeat(0, 3).Select(_ => CollectNews()).ToList();
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.
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.
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