Search code examples
c#expression-trees

How to refactor this into generic Expression?


How can I refactor this C# code into one generic GetBy(string property, string search) method?

public MyModel GetByName(string name)
    {
        return GetAll().SingleOrDefault(d => string.Equals(d.Name, name, StringComparison.OrdinalIgnoreCase));
    }

    public MyModel GetByUrl(string url)
    {
        return GetAll().SingleOrDefault(d => string.Equals(d.Url, url, StringComparison.OrdinalIgnoreCase));
    }

GetAll() gives back List of MyModel, so this can be an issue also, it is not an IQueryable result.


Solution

  • You could but it's not a good way to maintain type safety. Alternatively, you could do it like that:

    public MyModel GetBy<T>(Func<MyModel, T> property, T value) where T : IEquatable<T> {
            return GetAll().SingleOrDefault(d => property(d).Equals(value));
        }
    
    GetBy(m => m.Name, "Foo");
    

    Or:

        public MyModel GetBy(Func<MyModel, bool> predicate) {
                    return GetAll().SingleOrDefault(predicate);
                }
    
    GetBy(m => m.Name.Equals("Foo", StringComparison.OrdinalIgnoreCase));