[英]LINQ: How do I find all the objects whose Array property contains a particular value using LINQ
I've been searching for a while and could not find exactly what I need. 我已经搜寻了一段时间,但找不到确切的需求。
This questioning might be devoted, since, I suspect there are some alike questions here already. 因为我怀疑这里已经存在一些类似的问题,所以可能会提出这个问题。 But I think I have a specific case.
但我认为我有一个具体案例。
I have an object User that contains the property as Array of permissions. 我有一个对象User,其中包含属性为“权限数组”。
I'm looking for the correct way to grab all the users with a particular permission. 我正在寻找正确的方式来获取具有特定权限的所有用户。
I tried the following: 我尝试了以下方法:
List<User> users = UserRepository.GetUser().Where(u => u.Permissions[0].Equals("MyPermission")).ToList();
When doing this, I'm getting an error: 这样做时,出现错误:
"Index was outside the bounds of the array."
“指数数组的边界之外。”
What is the correct way of doing this? 正确的做法是什么?
Using .Any() is a safe way 使用.Any()是一种安全的方法
List<User> users = UserRepository.GetUser()
.Where(u => u.Permissions.Any(x => x.Equals("MyPermission"))
.ToList();
You get an exception because you blindly index Permissions
with [0]
, without checking that it has any values at all. 之所以会出现异常,是因为您用
[0]
盲目索引了Permissions
,而没有检查它是否有任何值。
Adding a check for length would fix this problem, but it wouldn't catch "MyPermision"
outside the initial position. 添加长度检查可以解决此问题,但不会在初始位置之外捕获
"MyPermision"
。
You can fix this by using Contains(...)
: 您可以使用
Contains(...)
解决此问题:
// Construct a MyService.UserPermissions object for searching
var targetPermission = new MyService.UserPermissions("MyPermission");
var users = UserRepository
.GetUser()
.Where(u => u.Permissions.Contains(targetPermission))
.ToList();
Edit: Since it turns out that you are looking for a permission with a specific PermissionName
, you cannot use Contains
. 编辑:由于事实证明您正在寻找具有特定
PermissionName
,因此不能使用Contains
。 You need to use Any
instead: 您需要改用
Any
:
var users = UserRepository
.GetUser()
.Where(u => u.Permissions.Any(p => p.PermissionName == "MyPermission"))
.ToList();
利用空传播来跳过没有权限对象的用户,并检查数组长度以避免超出范围的异常:
List<User> users = UserRepository.GetUser().Where(u => u.Permissions?.Length > 0 && u.Permission[0] == "MyPermission").ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.