sharp bites

standing on the shoulders of giants

Ayende's Challenge

Ayende challenged the whole intarweb to resolve a problem similar to the ones he uses in his job interviews. It goes like this:
The task is listing the first 10 products that we can sell to a customer. The UI is console application, and the database design and data access method are whatever you want.

Additionally you have to filter those products according to some arguments given as input parameters to the application (representing different categorizations of products).

Now, my solution. :)

public enum Category
{
PG13,
Vegetarian
}

public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public IList Categories { get; set;}

public override string ToString()
{
return string.Format("{0}\t{1}", Name, Price);
}
}

public class Filter
{
public static IEnumerable ApplyFilter(IEnumerable products, Category category)
{
return from p in products where p.Categories.Contains(category) select p;
}
}

class Program
{
static void Main(string[] args)
{
var categoryMapper = new Dictionary
{
{"-pg13", Category.PG13},
{"-vegetarian", Category.Vegetarian}
};

var products = new List
{
new Product {Name = "Milk", Price = 1.0M,
Categories = new List {Category.PG13, Category.Vegetarian}},
new Product {Name = "Bread", Price = 1.3M,
Categories = new List {Category.PG13, Category.Vegetarian}},
new Product {Name = "Sausage", Price = 2.5M,
Categories = new List {Category.PG13}},
new Product {Name = "Horror Movie", Price = 5.0M,
Categories = new List {Category.Vegetarian}}
};

var filteredResults = (IEnumerable) products;
foreach (string arg in args)
{
if (categoryMapper.ContainsKey(arg))
{
filteredResults = Filter.ApplyFilter(filteredResults, categoryMapper[arg]);
}
}

filteredResults = filteredResults.Take(10);

foreach (Product product in filteredResults)
{
Console.Out.WriteLine(product);
}
}
}

Comments