Search code examples
c#linq-to-sqllambdaanonymous-methods

C#: Is it possible to declare a local variable in an anonymous method?


Is is possible to have a local variable in an anonymous c# methods, i.e. in the following code I would like to perform the count only once.

IQueryable<Enquiry> linq = db.Enquiries;

if(...) linq = linq.Where(...);

if(...) linq = linq.Where(e => 
    (x <= (from p in db.Orders where p.EnquiryId == e.Id select p).Count() && 
        (from p in db.Orders where p.EnquiryId == e.Id select p).Count() <= y));

if(...) linq = linq.Where(...);

var result = (from e in linq select e);

Is there a "let" for anonymous functions?

Update: Note that I'm adding several Where clauses after this statement so I can't close with a select.

/Niels


Solution

  • I've run into a similar problem. The solution is to create a custom expression tree generating method.

    I asked my question on MSDN-forums. Please see the question and answer here: Reusing Where expressions.

    This may give you an idea on how to proceed, but I must admit that custom expression trees are not for the faint-hearted ;-)