I was getting help related to a previous question but then told to ask a new question related to it but the code given I run into an error:
public void AddPersonToCommunity(string person, string communityName)
{
var result = communities.Where(n => String.Equals(n.CommunityName, communityName)).FirstOrDefault();
if (result != null)
{
result.Add(new Person() { PersonName = person }); //no definition for add?
}
}
You can see the previous question here for more specifics: relationships in rest?
If I do var result = communities; result will then have the definition for Add so im not sure whats going on?
You're calling Where() which will return an IEnumerable<Community> (no Add method) and then FirstOrDefault() which returns a Community (also no Add method). Where would you expect an Add method to come from?
I suspect you really want:
if (result != null)
{
result.People.Add(new Person { PersonName = person });
}
... because Community.People is a list of the people in that community, right?
Note that if you do var result = communities; there will indeed be an Add method - but with a signature of Add(Community), not Add(Person).
It's important that you keep the types of everything straight. This actually has very little to do with LINQ. You'd have seen the same result if you'd tried:
Community community = new Community();
community.Add(new Person { PersonName = person });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With