【问题标题】:Search product name in List<Product>在 List<Product> 中搜索产品名称
【发布时间】:2014-06-22 16:40:22
【问题描述】:

该函数实现在列表中搜索产品。我在 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);
    }

【问题讨论】:

  • 当列表中没有匹配项时,最常见的返回null
  • 这个问题肯定需要更多答案哈哈。

标签: c# list search


【解决方案1】:

您提到的编译错误归结为您没有返回值如果没有找到匹配项。即使总是有匹配,编译器也不知道,所以它必须抱怨任何代码能够在没有返回值的情况下退出:

例如您现有的功能应为:

    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;
            }
        }   
        return null;    // <<< Return a value if nothing was found
    }

但是...

...正如您使用 C# 编写的那样,是时候开始使用 LINQ 来发挥自己的优势了。

迭代、搜索等是 LINQ 的设计目的。通过使用 LINQ,您可以编写更少的代码并变得更有效率,并且错误更少(假设标准做法是更多行 = 更多错误):

您的代码可以简单地变成:

static void Main(string[] args)
{
    Product res=new Product();
    Console.WriteLine("Enter the name of the product");
    string pname = Console.ReadLine();
    res = products.SingleOrDefault(x=>x.Name == ProductName);
}

有趣的x=&gt;x.Name == ProductName 被称为 lambda 表达式。它基本上就像一个小函数,传递每个值(如x)并返回比较x.Name == ProductName 的布尔结果。如果有帮助,请将 x 视为您脑海中的 C# this

SingleOrDefault 只返回 lambda 表达式返回 true 的第一项。如果没有匹配的项目,它将返回一个“默认值”,对于一个对象,它是null

在这种情况下,您可以使用多种 LINQ 方法。 Where(x=&gt;x.Name == ProductName) 将返回所有匹配项的集合(实际上是一个 iEnumerable)。 FirstOrdefault()SingleOrDefault 几乎完全相同。唯一的区别是 SingleOrdefault 意味着只有一个匹配项(您的产品数据就是这种情况)。 FirstOrDefault 表示可能有多个匹配项,但您不在乎哪个先出现。

基本上,我强烈建议您开始学习 LINQ 的好处,并停止编写函数来执行琐碎的单行查询操作。

【讨论】:

    【解决方案2】:

    为什么你需要一个单独的方法呢?使用 LinQ 通过某个属性查找对象,如下所示:

    string name = Console.ReadLine();
    var foundPropduct = products.FirstOrDefault(p => p.Name == name);
    

    如果找到产品,则为foundProduct,否则为null

    【讨论】:

    • 想解释一下否决票?这是一个有效的解决方案。
    • +1:这个答案同样有效(尽管SingleOrDefault 在语义上优于FirstOrDefault,前提是数据中最多只能有一个匹配项)。
    【解决方案3】:

    这样说:

    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");  
    }
    

    【讨论】:

    • 它仍然显示“并非所有代码路径都返回值”的错误。找到的产品必须存储在 Main() 方法中的哪个变量中?提前致谢。
    • 一个 C# 问题暗示这将是使用 Linq 的完美情况。编写多行方法来做与单行 Linq 相同的事情是浪费并且不允许优化。大多数其他答案用更少的代码做同样的事情。
    • @TrueBlueAussie:是的,你说得对:Linq 在这种情况下更简洁,但由于问题的作者是初学者,我认为简单的 foreach 循环更容易让他/她理解.只是对错误代码稍作修改。
    • 明白,但如果他们为我工作,我会立即指导他们如何使用简单的 LINQ 查询并停止浪费时间:)
    【解决方案4】:
    return products.Where( m => m.Name == ProductsName ).FirstOrDefault();
    

    对上面代码的一点解释。

    FirstOrDefault 与 First 几乎相同。不同之处在于它如何处理空集合。如果集合为空,则返回该类型的默认值。这种方法简化了代码。在某些程序中,它消除了异常。

    在这种情况下,当没有产品具有匹配的 ProductName 时,它​​将返回 null

    【讨论】:

    • 这是如何获得赞成票的? OP 显然是初学者,可能无法理解这段代码,而且这个答案也没有包含任何解释!
    • @Selman22 我不这么认为。还是添加了一些解释。干杯。
    • 是的,这个答案肯定需要向一个明显的新手解释。此外,使用Where FirstOrDefault 是没有意义的。只需将 FirstOrDefault 与 lambda 表达式一起使用(或者更好的是 SingleOrDefault,这在这个问题的语义上更好)。
    【解决方案5】:

    你可以这样做:

    var prod =products.SingleOrDefault(x=>x.Name == ProductName);
    
    return prod;
    

    你的方法是这样的:

    public static Product SearchProductsByName(string ProductsName, List<Product> products)
    
    {
    
                Product pd = products.SingleOrDefault(x=>x.Name == ProductName);
    
    
                return pd;
    }
    

    在我看来,您不需要制作单独的方法,而是使用SingleOrDefault

    【讨论】:

    • +1:这是最合适的答案如果最多匹配一个产品名称。而替代FirstOrDefault 做同样的工作SingleOrdefault 在语义上更好,当只能预期只有一个匹配最多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多