I'm trying to see if an INT exists inside a list of objects. In my best attempt, below, I created a class of Person and their list of Memberships (they only contain Ids). I'm checking to see if a specific integer exists in the Person's list of Memberships.
In the code below, the Person belongs to Membership ids 1, 3, and 4. I'm trying to create a LINQ statement that when given an Integer it will return a TRUE/FALSE value if that integer exists in the Person's membership.
I created two scenarios: x = 4 should return TRUE, while x = 6 should return FALSE, but for some reason they are both returning TRUE.
What am I doing wrong?
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)
}
}
p1.memberships.Any(a => a.id == incorrect)