计算列表中的项目 - ASP.NET C#

时间:2015-03-09 19:55:32

标签: c# asp.net count tolist

我的网站上有一个搜索功能,它从文本框控件中获取文本,将其与我数据库中的产品名称进行比较,将结果添加到列表中,然后在转发器中显示产品详细信息。

我想计算列表中的项目数,以便我可以显示一些文本,如

  

搜索结果'牛仔裤' (找到10个结果)

我已经拥有了牛仔裤的搜索结果'我可以解决如何计算结果变量列表的问题。

C#

protected void btnSearch_Click(object sender, EventArgs e)
    {
        string searchWord = txtWord.Text;

        ZaraEntities db = new ZaraEntities();

        var results = db.Products.Where(p => p.Name.Contains(searchWord));

        rptrSearch.DataSource = results.ToList();
        rptrSearch.DataBind();

        litResults.Text = "<p>" + "Search results for " + "'" + txtWord.Text + "'" + "</p>";

    }

1 个答案:

答案 0 :(得分:1)

试试这个:

protected void btnSearch_Click(object sender, EventArgs e)
{
    string searchWord = txtWord.Text;

    ZaraEntities db = new ZaraEntities();

    var results = db.Products.Where(p => p.Name.Contains(searchWord));

    rptrSearch.DataSource = results.ToList();
    rptrSearch.DataBind();

    litResults.Text = "<p>" + "Search results for " + "'" + txtWord.Text + "'" + " ("+ results.ToList().Count + ") Results found.</p>";

}

OR

    litResults.Text = "<p>" + "Search results for " + "'" + txtWord.Text + "'" + " ("+ results.ToList().Count() + ") Results found.</p>";

编辑: 如果这样做会更好:

    litResults.Text = string.Format("<p>Search results for {0} ({1}) Results found.</p>",txtWord.Text,results.ToList().Count);