ninja239
ninja239
CC#
Created by ninja239 on 8/10/2023 in #help
❔ How do I use LINQ to get Friends younger than 50?
I have a class Friend:
class Friend
{
public DateTime BirthDate;
public string PhoneNumber;
public string Name;
public string Id;
public Friend(string name, string BirthDate, string PhoneNumber)
{
this.Name = name;
this.BirthDate = DateTime.Parse(BirthDate);
this.PhoneNumber = PhoneNumber;
this.Id = Guid.NewGuid().ToString();
}
public Friend(string name, DateTime BirthDate, string PhoneNumber)
{
this.Name = name;
this.BirthDate = BirthDate;
this.PhoneNumber = PhoneNumber;
this.Id = Guid.NewGuid().ToString();
}
}
class Friend
{
public DateTime BirthDate;
public string PhoneNumber;
public string Name;
public string Id;
public Friend(string name, string BirthDate, string PhoneNumber)
{
this.Name = name;
this.BirthDate = DateTime.Parse(BirthDate);
this.PhoneNumber = PhoneNumber;
this.Id = Guid.NewGuid().ToString();
}
public Friend(string name, DateTime BirthDate, string PhoneNumber)
{
this.Name = name;
this.BirthDate = BirthDate;
this.PhoneNumber = PhoneNumber;
this.Id = Guid.NewGuid().ToString();
}
}
I have a list of friends called "friends":
var friends = new List<Friend>{
new Friend("Linus", "01/01/1970", "707-419-4447"),
new Friend("Scott", "10/10/1970", "801-224-7513"),
new Friend("Charlie", DateTime.Parse("01/01/1999"), "801-225-8597")
};
var friends = new List<Friend>{
new Friend("Linus", "01/01/1970", "707-419-4447"),
new Friend("Scott", "10/10/1970", "801-224-7513"),
new Friend("Charlie", DateTime.Parse("01/01/1999"), "801-225-8597")
};
and I want to get all Friends whose birth dates were less than 50 years ago. To do that, I say:
var youngFriendsQuery =
from friend in friends
where (friend.BirthDate - now).TotalDays < 50*365
select friend;
var youngFriendsQuery =
from friend in friends
where (friend.BirthDate - now).TotalDays < 50*365
select friend;
but apparently all 3 Friends match. How do I fix this?
11 replies