简体   繁体   中英

Help with Linq query, need to set ID based on results of a sub-query

My link query currently looks like:

var products =
(
    from p in products
    where !p.parentID.HasValue          
    select new ProductList
    {
        Name = p.Name,
        WarehouseID = p.WarehouseID,
        IsInStock = products.Any(p1 => p1 ... )
    }       
).ToArray();

What I need to happen according to business rules is:

If IsInStock is set to true , I need to assign the value for WarehouseID from p1.WarehouesID .

How can I do this?

You could use a let statment:

var products =
  (
   from p in products
   where !p.parentID.HasValue
   let p1Id = products.Where(p1 => p1 ... ).Select(p1 => p1.WarehouseID).FirstOrDefault()
   select new ProductList
   {
    Name = p.Name,
    WarehouseID = p1Id == 0 ? p.WarehouseID : p1Id,
    IsInStock = p1Id != 0
   }


  )
  .ToArray();

Unfortunately, this isn't as straightforward as you might like. Nonetheless, here's a way to do it (assuming that WarehouseID is an int ):

var products =
(
    from p in products
    where !p.parentID.HasValue

    select new ProductList
    {
        Name = p.Name,
        WarehouseID = (int)(products.Where(p1 => p1 ... ).Select(p1 => (int?)p1.WharehouseID).FirstOrDefault() ?? p.WarehouseID),
        IsInStock = products.Any(p1 => p1 ... )
    }


)
.ToArray();

By way of explanation, the casts to int? and int are required, since FirstOrDefault on a result expecting an int would return 0 , not a null int? . I've cast it to an int? here to allow us to determine if the result is, in fact, null .

Don't put .ToArray() at the end.

Then just add the condition:

if (IsInStock()) 
 products = products.where(p => p.WarehouseID > 10);
else
 products = products.where(p => p.WarehouseId < 10);

After everything, just add return .ToArray() and the query will be executed with the ifs.

Got the point?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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