gpt4 book ai didi

c# - 如何将项目添加到 IEnumerable SelectListItem

转载 作者:太空狗 更新时间:2023-10-30 00:07:15 26 4
gpt4 key购买 nike

我正在尝试将一个项目添加到 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;
}

最佳答案

问题是你的变量类型是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;
}

关于c# - 如何将项目添加到 IEnumerable SelectListItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27235295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com