Posted by: Cirilo Meggiolaro | 03/7/2009

Tip of the day #144 – LINQ query operator – let

LINQ has an operator keyword named “let” that allows the result of sub expressions to be stored and then queried again. It may be initialized with a range variable and it cannot be initialized more than once.

How to..

Let’s assume we have a class of Customer type that stores a list of Orders as described on classes below:

public class Customer
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }

public class Order
    public int ID { get; set; }
    public int Items { get; set; }
    public decimal BilledTotal { get; set; }

Based on a valid list of customers named customers, we are going to get the customers that have Orders with total value greater than 1000. The first step is to store the customer orders using the let keyword and then query orders that have the property BilledTotal greater than 1000.

List<Customer> customers = new List<Customer>();

var customersQuery = (from cust in customers
                                      let orders = cust.Orders
                                   from custOrder in orders
                                 where custOrder.BilledTotal > 1000
                                 select cust).Distinct();

foreach (var customer in customersQuery)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: