tags:

views:

72

answers:

2

Having the following C# linq query:

var result =
 from member in members
 let BestPriceLength =
  (from lumber in lumbers
  where member.Thickness == lumber.Thickness && member.Width == lumber.Width && member.Length <= lumber.Length
  select lumber).Min(l => l.Price / l.Length)
            let BestLengthFromBestPrice = ??????
 select new 
  {
   Member = member,
   MemberLength = member.Length,
   BestLengthFromBestPrice ,
   Ratio = member.Length / BestLengthFromBestPrice,
  };

I don't know how to get the lumber's length chosen by for the BestPriceLength variable into the other parts of the result.

Anyone with a clever idea?

A: 

If I understood your question correctly, you could do something like this:

from member in members
  let theLumber=
   (from lumber in lumbers
    where member.Thickness == lumber.Thickness && member.Width == lumber.Width &&
    member.Length <= lumber.Length
    select lumber)
  let BestPriceLength = theLumber.Min(l => l.Price / l.Length)
  let BestLengthFromBestPrice = theLumber.Length
  //etc...
Konamiman
Is it optimal? I'm worried that using theLumber in two places would iterate the list twice... Am I right in assuming that?
Stecy
theLumber is obtained only once, then cached and used in the other two "let" statements.
Konamiman
A: 

Here's what I've done, after some hints from pst left in the comments (too bad he did not leave an answer I could accept!):

var result =
        from member in members
        let bestLumber =
                (from lumber in lumbers
                where member.Thickness == lumber.Thickness && member.Width == lumber.Width && member.Length <= lumber.Length
                orderby lumber.Price / (decimal)lumber.Length
                select lumber).First()
        select new 
                {
                        Member = member,
                        MemberLength = member.Length,
                        BestLumber = bestLumber,
                        Ratio = member.Length / bestLumber.Length,
                };
Stecy