gpt4 book ai didi

c# - LINQ 查询中的增量

转载 作者:行者123 更新时间:2023-11-30 14:57:08 25 4
gpt4 key购买 nike

您好,我有以下代码,它返回 Listitem 类型的列表。我想为每个选定的 ListItem 增加一个值。

public static List<System.Web.UI.WebControls.ListItem> GetMyCompassTUTListContent(List<int> ContentID, Int32 CountryID)
{
int Counter = 0;
List<System.Web.UI.WebControls.ListItem> litems = new List<System.Web.UI.WebControls.ListItem>();
using (DbDataContext objContext = new DbDataContext())
{
if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
{
litems = objContext.Contents.Where(x => ContentID.Contains(x.ID)).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, y = (y + 1) }).ToList();
}
else
{
litems = objContext.ContentCountries.Where(x => ContentID.Contains(x.ContentID) && x.CountryID == CountryID).Select(x => new System.Web.UI.WebControls.ListItem { Text = x.Text, Value = (Counter + 1).ToString() }).ToList();
}
}
return litems;
}

请帮帮我。我无法做到这一点,因为我无法找到如何在递增后将值重新分配给变量计数器的方法。

提前致谢

最佳答案

Select 的重载也提供了当前项的索引。你可以用那个。但是,大多数数据库查询提供程序不支持它,因此您需要进行数据库查询,然后确保调用 SelectEnumerable 重载以添加索引:

public static List<ListItem> GetMyCompassTUTListContent(
List<int> ContentID, Int32 CountryID)
{
//Note this is IEnumerable, not IQueryable, this is important.
IEnumerable<string> query;
using (DbDataContext objContext = new DbDataContext())
{

if (CountryID == (int)MyCompassBLL.Constants.Country.Australia)
{
query = objContext.Contents.Where(x => ContentID.Contains(x.ID))
.Select(x => x.Text);
}
else
{
query = objContext.ContentCountries
.Where(x => ContentID.Contains(x.ContentID)
&& x.CountryID == CountryID)
.Select(x => x.Text);
}
return query.Select((text, index) => new ListItem
{
Text = text,
Value = (index + 1).ToString(),
})
.ToList();
}
}

关于c# - LINQ 查询中的增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21240346/

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