Home > front end >  Can you help simplify this linq?
Can you help simplify this linq?

Time:10-06

public List<Order> GetGrainOrders()
{
    var orders = GetOrdersJson();
    orders = orders.Select(o => o)
                   .Where(o => o.LineItems.Any(i => i.Sku.Contains("GRNS")))
                   .ToList();
    orders.ForEach(o => o.LineItems.RemoveAll(i => !i.Sku.Contains("GRNS")));
    return orders;
}

Can you help me simplify these linq queries?

Cheers

CodePudding user response:

This is simpler & may be more efficient:

public List<Order> GetGrainOrders() {
    return GetOrdersJson()
            .Select(o => {
                o.LineItems = order.LineItems.Where(i => i.Sku.Contains("GRNS")));
                return o;
            })
            .Where(o => o.LineItems.Count() != 0)
            .ToList();
}

CodePudding user response:

There might be some minor changes that could at least remove a bit of code...not that it is necessarily "simpler".

public List<Order> GetGrainOrders()
{
    var orders = GetOrdersJson()
      .Where(o=>o.LineItems.Any(i=>i.Sku.Contains("GRNS")))
      .ToList();
    orders.ForEach(o => o.LineItems.RemoveAll(i => !i.Sku.Contains("GRNS")));
    return orders;
}

CodePudding user response:

I would add LineItems in your select clause.

var orders = GetOrdersJson();
orders = orders.Select(o => new Order
{
    // Assign the other fields you need from Order here
    LineItems = o.LineItems.Where(i => i.Sku.Contains("GRNS")).ToList()
})
    .Where(o => o.LineItems.Any(i => i.Sku.Contains("GRNS")))
    .ToList();

return orders;
  •  Tags:  
  • c#
  • Related