I have this line of code: nameof(Class) + "." + nameof(Class.Property). Is there a simpler way to write this? Can I write an extension for this?
I can’t think of a way of simplifying it.
You can’t make it an extension method, because you don’t have an instance of Class to work with (as far as I can see).
You can make it into a method, but it would be quite a bit more complex, because it would need to take an Expression as a parameter, then you’d use it something like this (edit: actually, this would only work for static properties, it would get even more complex for non-static properties):
But the real question is… why? What are you trying to solve with this?
I’m building an API, so I want to be able to sort using a property name as a string using IQueryable<T>.OrderBy(propertyname). I have a class that maps the property names of my DTO to the property names of my entity.public class ClassA{public Guid Id { get; set; }public string Name { get; set; }public Guid ClassBId { get; set; }public ClassB ClassB { get; set; }}public class ClassB{public Guid Id { get; set; }public string Name { get; set; }}public class ClassADto{public Guid Id { get; set; }public string Name { get; set; }public Guid ClassBId { get; set; }public string ClassBName { get; set; }}
In order to be able to sort on ClassBName I need to map the string ClassBName to ClassB.Name. I’ll have to do this quite a few times, so I was wondering if there was a “nicer” way to do this.
Edit: I’ll just stick with nameof(Class) + "." + nameof(Class.Property). Thanks for the advice!