Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c# - Convert List to IEnumerable<SelectListItem>

Tricky problem here. I'm trying to convert items for a list to IEnumerable<SelectListItem>.

Lists

dynamicTextInDatabase simply returns all the Enums that are used in my database. Currently only returns 1 and 2. The data class simple holds an int value.

dynamicTextEnumsInDatabase is the same list as above just in the class that actually stores my Enums.

dynamicTextEnumsAll is a list of all the Enums that are available in my application. Currently: 1, 2 and 3.

dynamicTextEnumsAvaiable is a list of all the unused Enums. It combines All the Enums and then removes the ones that are in the database list.

I need to pass the dynamicTextEnumsAvaiable to my View via the ViewBag to display in a drop-down list. However, It must be IEnumerable<SelectListItem> rather than a List.

Code

        var dynamicTextInDatabase = new List<DynamicTextEnumData>();
        var dynamicTextEnumsInDatabase = new List<DynamicTextEnum>();
        var dynamicTextEnumsAll = new List<DynamicTextEnum>();
        IEnumerable<SelectListItem> list;

        using (var proxy = new Proxy<IDynamicText>())
        {
            dynamicTextInDatabase = proxy.Channel.DynamicTextGetActiveEnums(Helper.GetCallingUser());
        }

        foreach (DynamicTextEnumData item in dynamicTextInDatabase)
        {
            var dynamicTextEnum = (DynamicTextEnum)item.DynamicTextEnum;
            dynamicTextEnumsInDatabase.Add(dynamicTextEnum);
        }

        foreach (DynamicTextEnum item in Enum.GetValues(typeof(DynamicTextEnum)))
        {
            dynamicTextEnumsAll.Add(item);
        }

        var dynamicTextEnumsAvaiable = dynamicTextEnumsAll.Except(dynamicTextEnumsInDatabase).ToList();

        if (dynamicTextEnumsAvaiable.Count == 0)
        {
            TempData["Error"] = "To update the text of a message or warning, please select it from the grid below.";
            return RedirectToAction("Index");
        }

        ViewBag.AvaiableEnums = dynamicTextEnumsAvaiable;
        return View();
question from:https://stackoverflow.com/questions/20380994/convert-list-to-ienumerableselectlistitem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe try this? (untested)

ViewBag.AvaiableEnums = dynamicTextEnumsAvaiable.Select(x => 
                                  new SelectListItem() 
                                  {
                                      Text = x.ToString()
                                  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...