开发者

IEnumerable<SelectListItem> error question

开发者 https://www.devze.com 2022-12-24 13:50 出处:网络
I have the following code, but i`m having error of Error 6 foreach statement cannot operate on variables of type \'int\' because \'int\' does not contain a public definition for \'GetEnumerator\' C

I have the following code, but i`m having error of

Error 6 foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator' C:\Dev\DEV\Code\MvcUI\Models\MappingModel.cs 100 13 MvcUI

How can I solve this?

Note:

string [] projectID;


    Class Project
    {
        int id {get; set;}
        string Name {get;set;}
    }

 public IEnumerable<SelectListItem> GetStudents()
    {
        List<SelectListItem> result = new List<SelectListItem>();
        foreach (var id in Convert.ToInt32(projectID))
        {
            foreach( Project project in Project.Load(id))
                result.Add(new SelectListItem
                {
                    Selected =  false,
                    Text = emp.ID.ToString(),
                    Value = emp.Name
                });

            return result.A开发者_开发问答sEnumerable();
        }


    }


It looks like projectID is a string[] and you're trying to convert it to a int[]. If so you can do the following to make the foreach loop work

foreach (var id in projectID.Select(x => Convert.ToInt32(x))) {
  ...
}


Your tring to convert the strings in projectId to int in the foreach statement. Put the convert inside the foreach.

Try this

public IEnumerable<SelectListItem> GetStudents()
{
    List<SelectListItem> result = new List<SelectListItem>();
    foreach (var id in projectID)
    {
        int intId = Convert.ToInt32(id);
        foreach( Employee emp in Project.Load(intId))
            result.Add(new SelectListItem
            {
                Selected =  false,
                Text = emp.ID.ToString(),
                Value = emp.Name
            });
    }
    return result.AsEnumerable();
}

There are other problems. You are returning from inside the loop so you are only ever going to get this to work for the first id. I tried to correct that in the above code


Convert.ToInt32(projectID) would not return a collection of ints, it would return a single Int instance, therefore you cannot use a foreach statement for it.

What are you trying to achieve?


public IEnumerable<SelectListItem> GetStudents()
{
    return from id in projectID
           from employee in Project.Load(int.Parse(id))
           select new SelectListItem
           {
               Text = employee.ID.ToString(),
               Value = employee.Name
           };
}

Remark: your naming conventions are a little strange: GetStudents using Project.Load which returns employees.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号