Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern for ordering and filtering data?

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?

like image 898
magnattic Avatar asked Jan 12 '12 15:01

magnattic


People also ask

Which design pattern is used in collections sort uses?

Collections. sort() uses Strategy pattern.

Which of the design pattern is used to to access the elements?

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.

What is the behavior of filter pattern?

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.


1 Answers

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);
like image 77
codeConcussion Avatar answered Oct 25 '22 08:10

codeConcussion