I have two classes.
public class User
{
public int UserId { get; set;}
public string UserName { get; set; }
}
public class UserTimes
{
public int UserId { get; set; }
public DateTime Timestamp { get; set; }
}
Now I want to search for users based on recorded timestamps from UserTimes. I have my data from users as IQueryable<User>
the UserTimes as IQueryable<UserTimes>
How can I find all users from my first IQueryable, where the userId is in my second IQueryable and the Timestamp is > xxxx
This can be achieved using a .Join
in a linq query. The following is an example of retrieving all users with a time stamp greater than 2 days ago. Notice that only Huey and Dewey have time stamps that qualify; Louie only has older time stamps, thus the results will be as follows:
1::Huey
2::Duey
Here's the code listing:
void Main()
{
var users = new List<User> {
new User { UserId = 1, UserName = "Huey" },
new User { UserId = 2, UserName = "Dewey" },
new User { UserId = 3, UserName = "Louie" }
};
var times = new List<UserTimes> {
new UserTimes { UserId = 1, Timestamp = DateTime.Now.AddDays(-1) },
new UserTimes { UserId = 1, Timestamp = DateTime.Now.AddDays(-2) },
new UserTimes { UserId = 2, Timestamp = DateTime.Now.AddDays(-1) },
new UserTimes { UserId = 2, Timestamp = DateTime.Now.AddDays(-2) },
new UserTimes { UserId = 3, Timestamp = DateTime.Now.AddDays(-3) },
new UserTimes { UserId = 3, Timestamp = DateTime.Now.AddDays(-3) },
};
var recentUsers = times
.Join(users, t => t.UserId, u => u.UserId, (t, u) => new { User = u, Times = t })
.Where(t => t.Times.Timestamp > DateTime.Now.AddDays(-2))
.Select(t => t.User);
recentUsers.ToList().ForEach(u => Console.WriteLine($"{u.UserId}::{u.UserName}"));
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
public class UserTimes
{
public int UserId { get; set; }
public DateTime Timestamp { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.