dimanche 21 janvier 2018

How to implement Strategy pattern using Generics in C#

I have a string

string partialCityName

and a generic list .

var city = List<City>

I want to do two things:

1. Filter the list based on the name and I am doing that like this:

var availableCities = cityList.Where(f => f.CityName.StartsWith(partialCityName));

2. Get a list of chars based on the above var "availableCities" and I am doing that like this.

var nextAvailableCharacters = avalibleCities .
          Where(s => s.CityName.Length > partialCityName.Length).
          Select(s => s.CityName.Substring(partialCityName.Length)[0]).ToList();

Currently this is happening in one method, and is working. However I am trying to understand design patterns, and am trying to implement the Strategy pattern.

So the first question is, is this the correct pattern to use? If so how?

This is what I have got so far.

public interface IFilterStrategy
{
   List<T> Filter<T>(List<T> filterThisData, string filter);
}

Then:

    public class FilterCityStrategy : IFilterStrategy
    {

        public List<City> Filter<City>(List<City> filterThisData, string partialCityName)
        {
            //Fails to compile cityName not member of f 
            return filterThisData.Where(f => f.CityName.StartsWith(partialCityName));
        }
    }

Aucun commentaire:

Enregistrer un commentaire