该功能实现了列表中产品的搜索.我在if循环中的返回类型中收到错误.如果找到产品应该返回什么类型,如果找不到productname则返回类型应该是什么?应该将值返回到main()方法中的哪个变量?
namespace Sample
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
public static Product SearchProductsByName(string ProductsName, List<Product> products)
{
Product pd;
pd= new Product();
foreach (Product rs in products)
{
if (ProductsName == rs.Name)
{
return pd;
}
}
}
}
static void Main(string[] args)
{
Product res=new Product();
Console.WriteLine("Enter the name of the product");
string pname = Console.ReadLine();
res=SearchRestaurantsByName(pname , products);
}
Run Code Online (Sandbox Code Playgroud)
就这样说:
public static Product SearchProductsByName(string ProductsName, List products) {
foreach (Product rs in products)
if (ProductsName == rs.Name)
return rs; // <- The product found
return null; // <- There's no such a product in the list
}
Run Code Online (Sandbox Code Playgroud)
编辑:至于Main方法,预期类似的东西:
static void Main(string[] args) {
// You should declare and fill in the products list
// where you'll be looking for the product
List<Product> products = new List<Product>() {
//TODO: Replace it with the actual products
new Product() {Name = "Product A"},
new Product() {Name = "Product B"},
new Product() {Name = "Product C"}
};
// Ask user for the product name
Console.WriteLine("Enter the name of the product");
string pname = Console.ReadLine();
// The product user's looking for
Product res = SearchRestaurantsByName(pname, products);
//TODO: change this for required response to user
if (res != null)
Console.WriteLine("The product is found");
else
Console.WriteLine("The product is not found");
}
Run Code Online (Sandbox Code Playgroud)