Posted by: Cirilo Meggiolaro | 11/12/2008

Tip of the day #29 – ILookup interface

Let’s check today the ILookup interface under the System.Linq namespace.

The name says it all. The object looks something up in a collection based on a key and an element. The key will be basically the rule to look up data and the element what you want to expose.

ILookup<TKey, TElement>

To clarify, let’s assume that your application has an object type named Furniture like the following code:

public class Furniture
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
public decimal UnitPrice { get; set; }
}

public enum Category
{
Bedroom,
LivingRoom,
Kitchen,
Patio
}

Object defined, it’s time to create a list of objects from the Furniture type.

List<Furniture> furniture = new List<Furniture>() {
new Furniture{ Id = 1, Category = Category.Bedroom, Name = “Mattress”, UnitPrice = 1299.00M } ,
new Furniture{ Id = 2, Category = Category.LivingRoom, Name = “Dinner Table”, UnitPrice = 850.00M } ,
new Furniture{ Id = 3, Category = Category.LivingRoom, Name = “Sofa”, UnitPrice = 600.00M } ,
new Furniture{ Id = 4, Category = Category.Kitchen, Name = “Microwave”, UnitPrice = 129.00M },
new Furniture{ Id = 5, Category = Category.Patio, Name = “Barbecue Grill”, UnitPrice = 619.00M }
};

Once the collection is ready you can use the ILookup interface to retrieve your objects based on a defined pattern:

ILookup<Category, string> listOfFurniture = furniture.ToLookup(cat => cat.Category, n => string.Format(“ID: {0} – Name: {1}”, n.Id, n.Name));

Using lambda expressions, the code above defines the category as the key (cat => cat.Category) and the furniture Id and name as the element group to expose (in the example concatenated using string.Format function).

To check the results you may loop through the ILookup object like the following code:

foreach (var item in listOfFurniture)
{
Console.WriteLine(item.Key.ToString());

foreach (string element in item)
{
Console.WriteLine(” {0}”, element);
}
}

Output:

ILookup interface output


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: