LINQ:按子列表中的值过滤

时间:2015-10-24 09:23:40

标签: c# linq

我已经获得了这样一个列表:

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 UserIdlistOfUserIds内的记录。

如果没有for循环,如何轻松实现这一目标?

1 个答案:

答案 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