2

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)

    }
}
3
  • Change Select to Where. Ex: bool y = p1.memberships.Where(a => a.id == incorrect).Any() Commented Apr 16, 2020 at 15:10
  • 5
    Or better, p1.memberships.Any(a => a.id == incorrect) Commented Apr 16, 2020 at 15:10
  • Yes, it is better use Any. thanks Jon Skeet. Commented Apr 16, 2020 at 15:12

2 Answers 2

5

Your code is converting the memberships into a list of bool, and then seeing if there are any members - which there are as you have a list like: [false, false, false]. What you want is this:

bool x = p1.meberships.Any(a => a.id == correct);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use List<T>.Exists(Predicate<T>) method here as well, it doesn't require using System.Linq namespace. Just pass the predicate as an argument to it

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.