How to convert a do-while loop into Linq

Sherpa 326 Reputation points
2022-01-13T19:52:56.507+00:00

I have the following code which calculates a given number of days in the past. I would like to know how to convert it into Linq.
public static List<DateTime> GetPreviousDates(int count, DateTime startDate, int interval)
{
List<DateTime> dates = new List<DateTime>();
int counter = 1;
do
{
dates.Add(startDate.AddDays(-(interval * counter)));
counter++;
count--;
} while (count != 0);

            return dates;
        }
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-01-13T20:05:29.403+00:00

    Check a solution:

    public static List<DateTime> GetPreviousDates( int count, DateTime startDate, int interval )
    {
        return Enumerable.Range( 1, count ).Select( c => startDate.AddDays( -c * interval ) ).ToList( );
    }
    

    However, the original loop probably works differently and incorrectly when count is zero.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.