Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method x times using linq

Tags:

c#

linq

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(){
...
}


like image 534
Pablitros Avatar asked Nov 27 '19 16:11

Pablitros


3 Answers

var lstNews = Enumerable.Repeat(0, 3).Select(_ => CollectNews()).ToList();
like image 145
Chris Yungmann Avatar answered Nov 17 '22 01:11

Chris Yungmann


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.

like image 6
Nick Proud Avatar answered Nov 17 '22 02:11

Nick Proud


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.

like image 5
Grzegorz Sławecki Avatar answered Nov 17 '22 02:11

Grzegorz Sławecki