Question

I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Web.UI.WebControls.ListItem'

public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}
Was it helpful?

Solution

You don't need to yield return from ... but simply return from ... or you could:

private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
{
    return results.Select(s => new ListItem(s));
}

or even get rid of this function and:

dropDown.Items.AddRange(items.Select(s => new ListItem(s)).ToArray());

OTHER TIPS

private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        return results.Select(x => new ListItem(x));
    }

yield return should refer to a single ListItem which would be returned in a 'lazy' way when the IEnumerable is iterated. Your linq expression is of type IEnumerable so there is a mismatch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top