I need to filter and order data entries after criteria that a user selects through a dropdown. Selectable will be things like "newest entries first", "oldest entries first", "lowest price first" etc.
I could just create an enum for the options and switch/case where I retrieve the data, but I'd rather do this in an easily extendable way.
What design pattern would fit the situation best?
Collections. sort() uses Strategy pattern.
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations.
Everyone has mentioned the strategy pattern. Just thought I'd post my simple implementation. No need to make it more complicated than necessary.
public enum SortMethod
{
Newest,
Oldest,
LowestPrice,
}
public class Foo
{
public DateTime Date {get;set;}
public decimal Price {get;set;}
}
...
var strategyMap = new Dictionary<SortMethod, Func<IEnumerable<Foo>, IEnumerable<Foo>>>
{
{ SortMethod.Newest, x => x.OrderBy(y => y.Date) },
{ SortMethod.Oldest, x => x.OrderByDescending(y => y.Date) },
{ SortMethod.LowestPrice, x => x.OrderBy(y => y.Price) }
};
...
var unsorted = new List<Foo>
{
new Foo { Date = new DateTime(2012, 1, 3), Price = 10m },
new Foo { Date = new DateTime(2012, 1, 1), Price = 30m },
new Foo { Date = new DateTime(2012, 1, 2), Price = 20m }
};
var sorted = strategyMap[SortMethod.LowestPrice](unsorted);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With