0

I need to implement a repository class that can let user search on different field of an object. After retrieve data from another service, I save the result to a Dictionary object, now I want to able filter result based on different object's properties. For example:

People {
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

Dictionary<int, People> rawData;

public List<People> GetByFirstName(string firstName) {
    if(string.IsNullOrEmpty(firstName)) {
         return new List<People>();
    }
    return rawData.Where(p => p.FirstName == firstName).ToList(i => i.Value);
}

public List<People> GetByLastName(string lastName) {
    if(string.IsNullOrEmpty(lastName)) {
         return new List<People>();
    }
    return rawData.Where(p => p.LastName == lastName).ToList(i => i.Key, i => i.Value);
}

Now I want to implement some sort of prototype pattern by using a helper function:

public List<People> SearchHelper(string searchValue, //need to change so that another can pass condition in here) {
    if(string.IsNullOrEmpty(lastName)) {
         return new List<People>();
    }
    return rawData.Where(// need to put customize condition here).ToList(i => i.Value);
}

The reason I want to have a prototype pattern here because I have ton of object's properties. Any suggestions are appreciated.

user247702
  • 23,641
  • 15
  • 110
  • 157
longlifelearner
  • 195
  • 1
  • 10
  • 1
    Is it viable to pass in a predicate function? Something like `List SearchHelper(Func filter) { return rawData.Values.Where(p => filter(p)).ToList(); }`? EDIT: Whereby your delegate would return `true` to include the object, and `false` to exclude: `SearchHelper(p => p.FirstName.StartsWith("B") && p.LastName.Length > 5);` would include all persons with their first name that starts with "B" and their last name is greater 6 letters. – Chris Sinclair Jun 11 '14 at 19:36
  • It's a perfect solution. I am trying to break through Func, Predicate concepts in C#. Thank you very much. I'll summarize your solution later in comment below. – longlifelearner Jun 11 '14 at 19:52

0 Answers0