我有两个表:
我想用分配了书籍的所有作者填充 ASP.NET 服务器控件下拉列表,并将每个作者的项目数附加到列表中。
我已经成功了。但是,仅此一个速度很慢,我计划再添加 3 或 4 个下拉列表来做同样的事情。有没有更好的方法改造下面的代码?
using (myDataContext db = new myDataContext())
{
//ddlAuthors
var authors = db.Authors.OrderBy(x=> x.text).Select(x => new
{
authorText= x.text,
authorId = x.authorID,
authorCnt = x.ItemAuthors.Count()
});
ddlAuthor.DataSource = authors;
ddlAuthor.DataTextField = "authorText";
ddlAuthor.DataValueField = "authorId";
ddlAuthor.DataBind();
foreach (ListItem item in ddlAuthor.Items)
{
foreach (var n in authors)
{
if(item.Value == n.authorId.ToString())
item.Text += string.Format(" ({0})", n.authorCnt);
}
}
}
最佳答案
这段代码可能是问题的一部分。
foreach (ListItem item in ddlAuthor.Items)
{
foreach (var n in authors)
{
if(item.Value == n.authorId.ToString())
item.Text += string.Format(" ({0})", n.authorCnt);
}
}
如果 ddlAuthor 有 10 个项目,您将执行此循环 100 次(在外循环中为 ddlAuthor.Items 中的每个项目执行 1 次,然后在内循环中为每个作者执行 1 次)。
如果在您的查询中您做了:
var authors = db.Authors.OrderBy(x=> x.text).Select(x => new
{
authorText= string.Format("{0} ({1})", x.text, x.ItemAuthors.Count()),
authorId = x.authorID
});
然后它在查询中绑定(bind),您不必遍历每个项目并附加计数。
我刚刚在 LinqPad 中尝试了类似的东西,它按照我想要的方式格式化了结果。
关于c# - 填写下拉列表并将分配的产品计数附加到每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5583886/