0

I'm working with a collection of DateTime with all dates from Date A to Date B. I will be handed a string which looks like 1234567, 1 is sunday, 2 is tuesday, etc.

Now, imagine I want to filter my dates collection using a string with the above configuration and we get the string 1004007, meaning we will have to filter our DateTime collection to only have dates which occur on a sunday, on a wednesday and a saturday.

How can I read the whole string, figure out which days I will be filtering from and then dynamically filter my collection according to those days of the week?

2 Answers 2

2

Give this a shot:

List<DateTime> dates = ...;
string filter = "1004007";

List<DateTime> filteredDates = dates.Where(d =>
    filter.Contains(((int)d.DayOfWeek + 1).ToString())).ToList();

Or, if you like, you can first construct a list of days that are your filter rather than just using the String.Contains function. If your list of dates is very large, doing this work up front could help performance:

List<DateTime> dates = ...;
string filter = "1004007";
var daysOfWeek = filter.Distinct().Where(c => c != '0')
                       .Select(c => (DayOfWeek)(int.Parse(c.ToString()) - 1))

List<DateTime> filteredDates = (from d in dates
                                join dw in daysOfWeek on d.DayOfWeek equals dw
                                select d).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, it is quite complete and explains the solution well.
1

Convert the day of the week to an integer, then a string, and use Contains to see if it is in your input string:

string days = "1004007";
var result = datetimes
   .Where(dt => days.Contains(((int)dt.DayOfWeek + 1).ToString()));

4 Comments

I'm sorry but I don't understand how I can loop through the string which says what days of the week we are filtering through to then filter the range of dates.
@Hallaghan: You don't have to loop through the string. Contains does that for you.
So it actually detects those numbers as being days inside the contains and filters the dates by them?
@Hallaghan: It finds the day of the week for each date time, converts it to an integer between 1 and 7, then converts the integer to a string (a single character). It then tests to see if this character is contained in your input string using string.Contains.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.