C#Linq检查对象列表中是否存在INT



我正在尝试查看对象列表中是否存在INT。在下面的最佳尝试中,我创建了一个Person类及其成员资格列表(它们只包含Id(。我正在检查Person的Membership列表中是否存在特定的整数。

在下面的代码中,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);

您也可以在这里使用List<T>.Exists(Predicate<T>)方法,它不需要使用System.Linq命名空间。只需将谓词作为参数传递给它

bool x = p1.memberships.Exists(a => a.id == correct);

最新更新