Newbie
Newbie

Reputation: 1111

Can this be done using LINQ/Lambda, C#3.0

Objective: Generate dates based on Week Numbers

Input: StartDate, WeekNumber

Output: List of dates from the Week number specified till the StartDate i.e. If startdate is 23rd April, 2010 and the week number is 1, then the program should return the dates from 16th April, 2010 till the startddate.

The function

public List<DateTime> GetDates(DateTime startDate,int weeks)
        {
            List<DateTime> dt = new List<DateTime>();
            int days = weeks * 7;

            DateTime endDate = startDate.AddDays(-days);
            TimeSpan ts = startDate.Subtract(endDate);
            for (int i = 0; i <= ts.Days; i++)
            {
                DateTime dt1 = endDate.AddDays(i);
                dt.Add(dt1);
            }

            return dt;
        }

I am calling this function as

DateTime StartDate = DateTime.ParseExact("20100423", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
            List<DateTime> dtList = GetDates(StartDate, 1);

The program is working fine.

Question is using C# 3.0 feature like Linq, Lambda etc. can I rewrite the program.

Why? Because I am learning linq and lambda and want to implement the same. But as of now the knowledge is not sufficient to do the same by myself.

Thanks.

Upvotes: 1

Views: 228

Answers (2)

Adriaan Stander
Adriaan Stander

Reputation: 166606

You can try something like

int weeks = 1;
var days = from d in Enumerable.Range(-weeks * 7, weeks * 7 + 1)
           select StartDate.AddDays(d);

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828170

Something like this:

public IEnumerable<DateTime> GetDates2(DateTime startDate, int weeks)
{
  var days = weeks * 7;
  return Enumerable.Range(-days, days + 1).Select(i => startDate.AddDays(i));
}

The Enumerable.Range method will return a sequence of integers within a specified range, in your example from -7 to 0.

After that I simply use each integer to substract that number of days from your initial startDate, building an IEnumerable<DateTime>.

Upvotes: 1

Related Questions