c# - C# Linq 检查对象列表中是否存在 INT
问题描述
我正在尝试查看对象列表中是否存在 INT 。在下面我的最佳尝试中,我创建了一个 Person 类及其成员资格列表(它们仅包含 Id)。我正在检查人员的成员资格列表中是否存在特定整数。
在下面的代码中,Person 属于 Membership id 1、3 和 4。我正在尝试创建一个 LINQ 语句,当给定一个 Integer 时,如果该整数存在于 Person 的成员资格中,它将返回一个 TRUE/FALSE 值。
我创建了两个场景:x = 4 应该返回 TRUE,而 x = 6 应该返回 FALSE,但由于某种原因,它们都返回 TRUE。
我究竟做错了什么?
public class Program
{
public class Person {
public int id {get;set;}
public string first {get;set;}
public string last {get;set;}
public List<Membership> memberships {get;set;}
}
public class Membership {
public int id {get;set;}
}
public static void Main()
{
Person p1 = new Person { id = 1, first = "Bill", last = "Jenkins"};
List<Membership> lm1 = new List<Membership>();
lm1.Add(new Membership {id = 1});
lm1.Add(new Membership { id = 3 });
lm1.Add(new Membership { id = 4 });
p1.memberships = lm1;
int correct = 4; /* This value exists in the Membership */
int incorrect = 6; /* This value does not exist in the Membership */
bool x = p1.memberships.Select(a => a.id == correct).Any();
bool y = p1.memberships.Select(a => a.id == incorrect).Any();
Console.WriteLine(x.ToString());
// Output: True
Console.WriteLine(y.ToString());
// Output: True (This should be False)
}
}
解决方案
您的代码正在将成员资格转换为 的列表bool
,然后查看是否有任何成员 - 因为您有一个类似的列表:[false, false, false]
. 你想要的是这样的:
bool x = p1.meberships.Any(a => a.id == correct);
推荐阅读
- c# - 将数据从 SQL 视图显示到 ASP.net 页面上的 ListView 中| 错误:NotSupportedException
- php - 通过functions.php添加的摘录 - 无法删除短代码
- c# - 创建动态 DTO
- excel - Excel 公式,用于根据将手动输入的日期创建日期范围
- c# - 在 ASP.NET MVC 和 MySQL 中通过 ODBC 绑定下拉列表
- powershell - 以提升的权限执行 ScheduledJob
- ios - Sinch 在后台接听电话
- microsoft-graph-api - 访问 Microsoft.Graph.User 用户主体名称属性 - Graph API
- java - 使用 Java 使用 MicrosoftTranslator v3 将 HTML 字符串从英语翻译成德语
- html - 四个项目的 Flex 容器对齐