C# C的搜索功能,如何检查是否有任何结果?

C# C的搜索功能,如何检查是否有任何结果?,c#,search,C#,Search,我为我的C控制台应用程序做了一个搜索功能,它工作得非常好! 但当我搜索一个不存在的产品时,它只返回空白。。我想测试是否有任何点击,如果没有,写出来给用户,如果有点击,显示正常的结果 我的搜索功能: public List<Product> SearchProduct(string searchresult) { SqlConnection conn = Database.openConnection(); List<

我为我的C控制台应用程序做了一个搜索功能,它工作得非常好! 但当我搜索一个不存在的产品时,它只返回空白。。我想测试是否有任何点击,如果没有,写出来给用户,如果有点击,显示正常的结果

我的搜索功能:

public List<Product> SearchProduct(string searchresult)
        {
            SqlConnection conn = Database.openConnection();
            List<Product> products = new List<Product>();
            using SqlCommand command = new SqlCommand(@"SELECT * FROM Products WHERE (ProductName Like @ProductName);", conn);
            {
                command.Parameters.AddWithValue("@ProductName", "%" + searchresult + "%");
                using SqlDataReader reader = command.ExecuteReader();

                Console.Clear();
                Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}", "ID:", "Produkt:", "Antal:", "SubKategori:", "Sidst redigeret af:\n");
                while (reader.Read())
                {
                    // Checking if reader has a value.. 
                    if (string.IsNullOrEmpty(reader.ToString()))
                    {
                        Console.WriteLine("No product with that criteria..\n");
                    }

                    Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}", 
                    reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
                }
                Console.WriteLine("\nTryk vilkårlig tast for at returnere");
                Console.ReadLine();
                Console.Clear();
                conn.Close();
            }
            return products;
        }
将循环更改为do/while,并检查初始读取器的结果。进入循环前阅读:

bool canRead = reader.Read();
if (canRead)
{
    do
    {
        // Checking if reader has a value.. 
        if (string.IsNullOrEmpty(reader.ToString()))
        {
            Console.WriteLine("No product with that criteria..\n");
        }

        Console.WriteLine("{0,-5} {1,-20} {2,-10} {3,-15} {4,-10}", 
        reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetInt32(4));
    }
    while (canRead = reader.Read());
}
else
{
    Console.WriteLine("No rows found.");
}

或者,填写产品列表并检查产品。根据Esko的评论,循环完成后进行计数。

reader.Read如果没有更多行,则返回false。当然,如果您是第一次调用它,那么如果没有任何行周期,它将返回false。但是在获得行之后如何检查它?@MichaelAggerholm您没有填充产品列表,在您实现了这一点之后,只需检查什么是产品就很容易了。countThank you Esko。我将和伯爵一起试一试