0

I have two methods that are fairly similar. I want to return entities based on whether one of its properties is null or an empty string. However, the properties of the entities are not shared. All properties are strings.

public List<Phone> GetPhones(){
    return context.Phones
                  .Where(p=> !(p.Number == null
                       || p.Number.Trim() == String.Empty))
                  .ToList();

public List<Remote> GetRemotes(){
    return context.Remotes
                  .Where(r => !(r.OEM == null
                       || r.OEM.Trim() == String.Empty))
                  .ToList();
}

Is it possible to create a method like:

public List<T> GetEntities(string property){
    return ...
}
Mister Epic
  • 16,295
  • 13
  • 76
  • 147
  • possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – BJ Myers Apr 16 '15 at 17:44

2 Answers2

1

Accessing the string properties can be done via reflection: Get property value from string using reflection in C#

The problem with what you're trying to do is that the source of the objects is different for each call, in addition to the property being accessed. To write a generic function you'll have to provide the source to the method as well as the property name.

A better approach might be to write a helper method that takes the source and a lambda expression to get the appropriate property:

public List<T> GetListOfNonEmpties<T>(IEnumerable<T> source, Func<T, string> property)
{
    return source.Where(n => !(property(n) == null
                        || property(n).Trim() == String.Empty))
                    .ToList();
}

Then use that in your other methods like this:

public static List<Phone> GetPhones()
{
    return GetListOfNonEmpties(context.Phones, p => p.Number);
}

public static List<Remote> GetRemotes()
{
    return GetListOfNonEmpties(context.Remotes, r => r.OEM);
}
Community
  • 1
  • 1
BJ Myers
  • 6,617
  • 6
  • 34
  • 50
1

Yes, but the following is probably a better general solution for you:

public IQueryable<Phone> GetPhones(){
    return context.Phones
                  .Where(p=> !String.IsNullOrWhiteSpace(p.Number));
}

public IQueryable<Remote> GetRemotes(){
    return context.Remotes
                  .Where(r => !String.IsNullorWhiteSpace(r.OEM));
}

It returns an IQueryable instead of List, so incase you want to put further restrictions on it, the execution can be delayed to include them as well. A "helper" function to generalize the functionality you are asking for isn't shorter or more concise than just using the String.IsNullOrWhiteSpace function on string. Assuming your context is a database, particularly a remote database, this is a significant improvement. If you don't have further restrictions now, you might (probably will?) in the future.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57