Friday, April 8, 2011

Using the All operator

I would like to see an example that makes the best use of the ALL operator when using a parent child reltaionship in LINQ. Can you show me one please?

From stackoverflow
  • If you want to get the parents along with whether all its childrens are active.

    from p in MyContext.Parents
    select new
    {
       p,
       ChildrensActive = p.Childrens.All(c=> c.IsActive)
    }
    
  • The All() extension method checks a predicate against all the items; for example, at execution:

    if(order.Lines.All(l=>l.IsClosed)) order.Close();
    

    (checks all lines are closed, and if so, closes the order)

    of in a query:

    var qry = from order in ctx.Orders
             where order.CustomerId = id
             select new {
                order.OrderId,
                IsShipped = order.Lines.All(l => l.IsShipped)
             };
    
    Viks : How would I handle a case where select all Customers having Order ..is this is a good candidate for 'All'?
    Marc Gravell : no; that would be Any - i.e. from cust in ctx.Customers where cust.Orders.Any() select cust;
  • Many LINQ examples here: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

  • IEnumerable<CD> goodCDs = CDs
      .Where(cd => cd.Songs.All(song => song.Rating > 6))
    

0 comments:

Post a Comment