Search code examples
c#linq

Call method x times using 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(){
...
}



Solution

  • 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.