No definition to add in linq syntax?

I was getting help related to the previous question, but then asked to ask a new question related to it, but with the code I ran into the 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 details: Vacation relationships?

If I do var result = communities;

, the result will have a definition for Add, so im not sure what is going on?

+3


source to share


2 answers


You call Where()

which method returns IEnumerable<Community>

(no Add

) and then FirstOrDefault()

which method returns Community

(also no Add

). Where do you expect the method to come from Add

?

I suspect you really want:

if (result != null) 
{ 
    result.People.Add(new Person { PersonName = person });
}

      

... because it Community.People

's a list of people in this community, right?



Note that if you do var result = communities;

, there will indeed be an Add method, but with a signature Add(Community)

, not Add(Person)

.

It is important that you keep all types straight. This has little to do with LINQ. You would see the same result if you tried:

Community community = new Community();
community.Add(new Person { PersonName = person });

      

+7


source


Adding to @ Jon's answer

There is an extension method Concat

for IEnumerable<T>

that allows you to logically combine two objects IEnumerable<T>

into one IEnumerable<T>

that spans both collections. You can extend this logic to add one item and then apply that to your current situation.



public static IEnumerable<T> Concat(this IEnumerable<T> enumerable, T value) {
  foreach (var cur in enumerable) {
    yield return cur;
  }
  yield return value;
}

...

result = result.Concat(new Person() { PersonName = person });

      

0


source







All Articles