0

In C-Sharp I have a Registrations class which basically creates a list of Questions items like this:

public partial class Registrations
{
    public Registrations()
    {
        this.Questions = new HashSet<Questions>();
    }

    public int id { get; set; }
    public virtual ICollection<Questions> Questions { get; set; }
}

My Questions class has a field called Title and it just gives the form field label.

public partial class Questions
{
    public int id { get; set; }
    public int registrationId { get; set; }
    public string Title { get; set; }
    public string Data { get; set; }
}

When a user creates a registration, he can add many questions with different titles. I want to check if a specific registration has a field with the title "City". I want to create a function in my Registrations class called hasCity which will return a boolean depending if the specific registration has that field.

public hasCity()
{
    Questions city = new Questions();
    city.Title = "City";
    if( this.Questions.Contains( city ) )
    {
        return true;
    }
    return false;
}

Now, the function above always returns false and I am guessing it is because I need to create some kind of method to check only the Title attribute for the string value City.

Tales
  • 1,829
  • 3
  • 33
  • 50
  • Maybe you need to change if condition like `(this.Qestions.Contains(city=="City"))` to give true. – Llazar Sep 19 '18 at 15:16

1 Answers1

1

I think you can use Any method in LinQ for this. Try the following. Hope to help, my friend:

public partial class Questions
    {
        public int id { get; set; }
        public int registrationId { get; set; }
        public string Title { get; set; }
        public string Data { get; set; }
    }

    public partial class Registrations
    {
        public Registrations()
        {
            this.Questions = new HashSet<Questions>();
        }

        public int id { get; set; }
        public virtual ICollection<Questions> Questions { get; set; }
        public bool HasCity(string titleCity)
        {            
            if (this.Questions.Any(x => x.Title.ToLower() == titleCity.ToLower()))
            {
                return true;
            }
            return false;
        }
    }
Tomato32
  • 2,145
  • 1
  • 10
  • 10
  • There is no definition for `Any` in ICollection, the only methods in the ICollection are: `Add`, `Clear`, `Contains`, `CopyTo`, `Count`, `Equals`, `GetEnumerator`, `GetHashCode`, `GetType`, `IsReadOnly`, `Remove` and `ToString`, your solution would be awesome otherwise. – Tales Sep 19 '18 at 17:36
  • 1
    @Tales: Just add the namespace: using System.Linq, my friend :)) – Tomato32 Sep 19 '18 at 17:41
  • Adding `using System.Linq` solved the problem, thank you. – Tales Sep 19 '18 at 17:43
  • @Tales: Well played, my friend :d – Tomato32 Sep 19 '18 at 17:46