我已经获得了这样一个列表:
int[] listOfUserIds = new int[]{1,2,5};
var groups = db.some_table.Where(x => x.isOpen == true)
.Select(t => new Models.XModel() {
Id = t.Id,
Name = t.name,
Users = t.Users.Where(x => x.Age > 25).Select(user => new Models.UsersModel()
{
Name = user.Name,
UserId = user.UserId
})
});
现在,从这个groups
列表中,我想获得至少有一个user
UserId
在listOfUserIds
内的记录。
如果没有for循环,如何轻松实现这一目标?
答案 0 :(得分:0)
在Where
子句中再添加一个条件:
x.Users.Any(user => listOfUserIds.Contains(user.UserId))
您的代码:
var groups = db.some_table.Where(x => x.isOpen == true && x.Users.Any(user => listOfUserIds.Contains(user.UserId)))
.Select(t => new Models.SomeModel() {
Id = t.Id,
Name = t.name,
Users = t.Users.Where(x => x.Age > 25).Select(user => new Models.UsersModel()
{
Name = user.Name,
UserId = user.UserId
})
});
要提高效果,您可以构建HashSet<int>
:
int[] listOfUserIds = new int[]{1,2,5};
HashSet<int> hash = new HashSet<int>(listOfUserIds);
var groups = db.some_table.Where(x => x.isOpen == true && x.Users.Any(user => hash.Contains(user.UserId)))
.Select(t => new Models.SomeModel() {
Id = t.Id,
Name = t.name,
Users = t.Users.Where(x => x.Age > 25).Select(user => new Models.UsersModel()
{
Name = user.Name,
UserId = user.UserId
})
});
使用HashSet<int>
,此操作hash.Contains(x.Id)
为O(1)而不是O(n)
listOfUserIds