该函数实现了列表中商品的搜索。我在 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);
}
最佳答案
这样说吧:
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
}
编辑:至于 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");
}
关于c# - 在 List<Product> 中搜索产品名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23488395/