c# - 填写下拉列表并将分配的产品计数附加到每个

标签 c# asp.net linq-to-sql

我有两个表:

enter image description here

我想用分配了书籍的所有作者填充 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/

相关文章:

c# - 使用 C# LINQ 按任一列分组

c# - linq select 语句与直接访问

asp.net - 如何手动将其他行添加到 ASP.NET gridview 的底部?

c# - 多个单词导致自动完成扩展程序出现问题

c# - 我如何使用 Linq/Linq to Sql 来执行此操作?

c# - 从列表中删除不调用 setter ?

c# - 在 Debug 模式下获取正确值,在 Release 模式下使用串行编程获取错误值

asp.net - Swashbuckle 重命名模型中的数据类型

c# - 通过更新父对象删除 Linq to SQL 中的相关对象

c# - 如何通过查找器界面在 Entity Framework 4 中查找实体? (适用于 Linq To Sql)