❔ How do I use LINQ to get Friends younger than 50?
I have a class Friend:
I have a list of friends called "friends":
and I want to get all Friends whose birth dates were less than 50 years ago. To do that, I say:
but apparently all 3 Friends match.
How do I fix this?
5 Replies
Note that 50 * 365 != 50 years, leap years are a thing
You'd also want to do Now - Birthdate, otherwise you'll get a negative number
Though really you'd want to just do Datetime.Now.AddYears(-50) and check their Birthdate is after that, then you don't have to worry about the above 2 points
thx
So something like this:
yeah I would think that should do the trick 👍 have a play to make sure
One thing to consider is if the input dates include a time, the age calculation will take that into accout and can give unexpected results if it's their birthday baeed on the day but not quite time wise
You could consider using DateOnly to avoid such problems
There's also TimeOnly for when the date doesn't matter.
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.