简体   繁体   English

从数组返回值

[英]Returning value from array

I have Inventories table and here I save all ProductId's who is below 10 or the same as 10 in Array 我有库存表,在这里我将所有低于10或等于10的ProductId保存在数组中

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

I know I have 3 products that Quantity is below 10 and when I run debug I can see those Ids. 我知道我有3种产品的数量低于10,并且在运行调试时可以看到那些ID。 So far so good. 到现在为止还挺好。

But When I want to retrieve names of those products, I just can get one of those 3 products... 但是当我想检索那些产品的名称时,我只能得到这3种产品中的一种...

To get names of those Products I wrote this code, but it's returning only one Product name. 为了获得这些产品的名称,我编写了此代码,但只返回一个产品名称。

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
}

Edited with a similar problem... 编辑有类似问题...

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

And my User email 和我的用户电子邮件

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

Because you are returning inside the loop. 因为您正在循环内返回。 So when the loop executes for the first item in the prId array, it gets only that product ( Basically a collection with only that product ) and since you have the return statement, it will be returned(exiting that code block).Your loop iteration will not be executed for the remaining items in the array. 因此,当循环针对prId数组中的第一项执行时,它仅获取该乘积( 基本上是仅包含该乘积的集合 ),并且由于您具有return语句,因此它将被返回(退出该代码块)。不会对数组中的其余项目执行。

You should use Contains method. 您应该使用Contains方法。 This allows you to query the Products which has ProductId matching to items inside the array ( the productIds you got from OrderNow method) 这使您可以查询具有与数组内的项目匹配的ProductId的Products(从OrderNow方法获得的productId)

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

   return context.Products
                 .Where(u => productIds.Contains(u.ProductId))
                 .Select(p => p.ProductName)
                 .ToArray();    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM