Posted by: Cirilo Meggiolaro | 02/5/2009

Tip of the day #114 – Take extension method – Enumerable class

The Take extension method from the Enumerable class is used to retrieve a specific number of elements in a collection.

Definition

The Take extension method has only one signature available:

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);

How to…

The syntax is pretty straightforward: myIEnumerableCollection.Take(numberOfItems);

Using the following class as our custom object:

public class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }
    public DateTime OrderDate { get; set; }
    public decimal BilledTotal { get; set; }
}

We have the following self-explanatory code:

/// Creates a list of orders.
List<Order> orders = new List<Order>()
{
    new Order() { OrderID = 1, CustomerID = 1, OrderDate = DateTime.Now, BilledTotal = 1234.56M },
    new Order() { OrderID = 2, CustomerID = 2, OrderDate = DateTime.Now, BilledTotal = 46.99M },
    new Order() { OrderID = 3, CustomerID = 2, OrderDate = DateTime.Now, BilledTotal = 999.00M },
    new Order() { OrderID = 4, CustomerID = 1, OrderDate = DateTime.Now, BilledTotal = 78.99M },
    new Order() { OrderID = 5, CustomerID = 1, OrderDate = DateTime.Now, BilledTotal = 8.99M },
    new Order() { OrderID = 6, CustomerID = 3, OrderDate = DateTime.Now, BilledTotal = 15.38M }
};

/// Creates an IEnumerable object with the first three
/// Order objects within the orders collection.
IEnumerable<Order> firstThree = orders.Take(3);

/// Loops through the results.
foreach (Order customerOrder in firstThree)
{
    /// Displays the order details.
    Console.WriteLine(“Customer ID: {0}, Order ID: {1}, Order Date: {2}, Total Value: {3}”, customerOrder.CustomerID, customerOrder.OrderID, customerOrder.OrderDate, customerOrder.BilledTotal);
}

The code above is just for this example purpose. You may call the Take extension method directly from the foreach loop:

foreach (Order customerOrder in orders.Take(3))
{ }

Output

Customer ID: 1, Order ID: 1, Order Date: 2/4/2009 10:52:58pm, Total Value: 1234.56
Customer ID: 2, Order ID: 2, Order Date: 2/4/2009 10:52:58pm, Total Value: 46.99
Customer ID: 2, Order ID: 3, Order Date: 2/4/2009 10:52:58pm, Total Value: 999.00

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

%d bloggers like this: