c# - 在 List<Product> 中搜索产品名称

标签 c# list search

该函数实现了列表中商品的搜索。我在 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/

相关文章:

c# - 如何创建一个以名称为参数的表?

python - 为什么我使用这样的for循环,但仍然收到IndexError?

python - 具有转换的重复数组

java - 在 Java 中返回一个对象

c++ - 二进制搜索代码未通过效率检查

c# - 只读自动实现的属性是否可能?

c# - 如何将屏幕坐标转换成相对坐标(winforms)?

c# - .NET 优先框架 3.5 的折线图

python - 使用Python按 block 解析文件并从每个 block 中提取信息

java - 改进 "search"输入字段的结果?