Foreach statement cannot operate on type ' ' because it does not contain a public definition for 'GetEnumerator'

StackOverflow https://stackoverflow.com/questions/23425848

  •  14-07-2023
  •  | 
  •  

سؤال

I have the following in my Api Controller:

[AcceptVerbs("POST")]
public Model.ViewModel.ContactSaveRequest DeleteMethod(Model.ViewModel.ContactSaveRequest methodsToDelete)
{
    var contactMethodRepos = new Model.ContactMethodRepository();

    foreach (var contactMethod in methodsToDelete)
    {
        contactMethodRepos.Delete(contactMethod);
        return contactMethod;
    }
}

This is my class defining a contact method

[JsonProperty("id")]
public int ID { get; set; }

[JsonProperty("contactID")]
public int ContactID { get; set; }

[JsonProperty("typeOfContactMethodID")]
public int TypeOfContactMethodID { get; set; }

[JsonProperty("text")]
public string Text { get; set; }

[JsonProperty("methodsToDelete")]
public IEnumerable<ContactMethod> methodsToDelete { get; set; }

ContactSaverequest class:

public class ContactSaveRequest
{
    [JsonProperty("contact")]
    public Contact Contact { get; set; }

    [JsonProperty("contactMethods")]
    public IEnumerable<ContactMethod> ContactMethods { get; set; }        
}

I have an array which pushes methods into it to be deleted (methodsToDelete). I am trying to use the Delete method on the array but keep getting the issue that contactSaveRequest doesn't contain a definition for GetEnumerator.

هل كانت مفيدة؟

المحلول

It sounds like you just want to use:

foreach (var contactMethod in methodsToDelete.ContactMethods)

You can't iterate over a ContactSaveRequest, but you can iterate over the IEnumerable<ContactMethod> that is returned by the ContactMethods property.

نصائح أخرى

Try to implement IEnumerable interface like this

public class ContactSaveRequest : IEnumerable {

}

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top