❔ LINQ Question - Thought I solved it...
I have a list of dates in month/day/year format, and I've created a hashset that holds ending quarter months:
My goal is to have a bool that checks if the
allDates
only contains Quarter months (3,6,9,12). Here's what I have so far:
21 Replies
What type is
allDates
?I think you want
All
instead of AnyThat too
If
allDates
is of type Date
you can also just get the month from it instead of doing that prefix check. It's not related but either way.i'm gonna guess they're strings (unfortunately)
And if you want to make it more complex, check if
month % 4 == 0
😛
That gets rid of your quarterEndMonths
fieldsorry of type string
Oo wait, you're right, that would work with a string tho?
No because you still need to get the prefix, which can either be 1 character or two
I would suggest you switch to a Date type or parse the strings when the application starts
You can use linq to call
Select
on the field and then use Date.(try)Parse
on each entryI forgot to mention that sometimes the
allDates
would only contain year strings 2017
, etc.You can use tryParse and just ignore invalid entries if you want?
Or do you need to explicitly return false on those?
Eh I'm checking format for our data when it's in monthly/quarterly/yearly. So if user selects monthly frequency, then i'm checking to ensure all their data is in monthly format, etc.
I think I'll just go with the
All()
So that is:
Correct? Still need the .Any() for the set?All
basically fixes your issue. I was trying to make a bit more sense of the situation 😛
If you're sure month/day/year is always the format used, not much can go wrongYes, it is. small app.
Just remember that if somebody sends
34739812649081234
as the date it will also be valid, because it starts with 3Just want to make sure I have the All/Any query above correct.
So if you want to avoid that, trying to parse a date before checking the prefix is still a good idea
Yeah, great point. We have some other prevents there where this would only be pulling from the dates column, and burden is on the client for this initial upload section.
Later when we process calculations, i do a TryParse()
Then it would be:
bool onlyContainsQuarters = allDates.All(x => Date.TryParse(x, out _) && quarterEndMonths.Any(prefix => x.StartsWith(prefix)));
I see, just remember client validation can be omitted
If it's a small app it's not as big of a deal I supposeAh ok that does make sense...
Forgot to add the
out
part. Fixed now.Thank you. I'm going to roll with just the:
For now, but may actually update to the date check because the does make more sense...
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.