从数组返回值

时间:2017-09-30 13:00:42

标签: arrays asp.net-mvc linq

我有库存表,在这里我保存所有低于10或与数组中的10相同的ProductId

public int[] OrderNow()
{
    return context.Inventory.Where(u => u.Quantity <= 10).Select(i =>i.ProductId)
                                                         .ToArray();
}

我知道我有3个产品,数量低于10,当我运行调试时,我可以看到那些ID。到目前为止一切都很好。

但是当我想要检索这些产品的名称时,我只能获得这3种产品中的一种......

要获取我编写此代码的产品的名称,但它只返回一个产品名称。

public string[] ProductName()
{
     var prId = OrderNow();
     foreach (var p in prId)
     {

       return context.Products.Where(u => u.ProductId == p)
                              .Select(p => p.ProductName).ToArray();
          // After one loop it's jumping foreach process .. I don't know why
     }
     return null; // I don't know what to write here, but I must to return something
}

编辑类似的问题......

public int[] OrderNow()
{
    return context.Inventory.Where(u => u.Quantity <= 10).Select(i =>i.DepartmentId)
                                                         .ToArray();
}

我的用户电子邮件

public string[] UserEmails()
{
   var departmentIds= OrderNow();   // Gets the array of product ids

   return context.Users
         .Where(u => u.IsInventoryAdmin == true)
                 .Where(u => departmentIds.Contains(u.DepartmentId)) // Here failing
                 .Select(e => e.Email)
                 .ToArray();    
}

1 个答案:

答案 0 :(得分:1)

因为你在循环中返回。因此,当循环对freq[tri]++数组中的第一个项执行时,它只获得该产品(基本上只包含该产品的集合)并且因为您拥有prId语句,它将被返回(退出该代码块)。不会对数组中的其余项执行您的循环迭代。

您应该使用return方法。这允许您查询ProductId与数组中的项匹配的产品(您从OrderNow方法获得的productIds)

Contains
相关问题