如何将项添加到IEnumerable SelectListItem

时间:2014-12-01 19:00:22

标签: c# asp.net-mvc-5

我正在尝试将项添加到IEnumerable SelectList。我有一个初始查询填充我的列表,然后我有一个查询来检查是否存在名为“INFORMATIONAL”的项目。如果没有,我需要将它添加到从我的初始查询返回的列表中。这是我的代码。它不喜欢list.Add(newItem)。任何援助将不胜感激。感谢

public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
    {
        IEnumerable<SelectListItem> list = null;

        using (var context = new AMPEntities())
        {
            // Queries DB for list of categories by AccountID
            var query = (from ca in context.CustomAlerts
                        where ca.AccountID == AccountID
                        orderby ca.AlertCategory
                        select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
            list = query.ToList();

            // Checks list to see if "INFORMATIONAL" already exists
            var item = (from l in list
                        where l.Value == "INFORMATIONAL"
                        select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();

            // If "INFORMATIONAL" is not present add it to list
            if (item == null)
            {
                var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
                list.Add(newItem);
            }
        }

        return list;
    }

3 个答案:

答案 0 :(得分:12)

问题是您的变量属于IEnumerable<SelectListItem>类型。将其更改为List<SelectListItem>或使用其他变量。

public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
    {
        List<SelectListItem> list = null;

        using (var context = new AMPEntities())
        {
            // Queries DB for list of categories by AccountID
            var query = (from ca in context.CustomAlerts
                        where ca.AccountID == AccountID
                        orderby ca.AlertCategory
                        select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
            list = query.ToList();

            // Checks list to see if "INFORMATIONAL" already exists
            var item = (from l in list
                        where l.Value == "INFORMATIONAL"
                        select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();

            // If "INFORMATIONAL" is not present add it to list
            if (item == null)
            {
                var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
                list.Add(newItem);
            }
        }

        return list;
    }

答案 1 :(得分:1)

基本上,你不能,因为IEnumerable不一定代表可以添加项目的集合。在SO上看到这个问题。

How can I add an item to a IEnumerable<T> collection?

答案 2 :(得分:0)

这是我提出的可能对某人有帮助的事情。甚至可能是我以后的日子。看看最后一行代码。

20.9