I my last post I introduced PropertyTranslator – an easy way to translate computed properties in a LINQ query into their implementation right before execution.
This post covers how PropertyTranslator enables you to use LINQ queries written towards properties of an interface, instead of the implementing class.
The Context
Let’s assume you’ve got an IPerson interface as follows:
public interface IPerson { string DisplayName { get; } }
Additionally there are the two classes Student and Teacher implementing the IPerson interface.
To keep your code base clean you pay great attention to the DRY principle and want to implement a search algorithm for filtering objects implementing IPerson only once in a single place:
public IEnumerable<T> Search<T>(IEnumerable<T> list, string name) where T : IPerson { return list.Where(p => p.DisplayName.Contains(name)); }
Implementation using PropertyTranslator
Implementing this using PropertyTranslator is straight forward:
public class Student : IPerson { private static readonly CompiledExpressionMap<Student, string> displayNameExpression = DefaultTranslationOf<Student>.Property(s => s.DisplayName).Is(s => s.Name + " (" + s.MatrNo + ")"); public string DisplayName { get { return displayNameExpression.Evaluate(this); } } public string Name { get; set; } public string MatrNo { get; set; } }
public class Teacher : IPerson { private static readonly CompiledExpressionMap<Teacher, string> displayNameExpression = DefaultTranslationOf<Teacher>.Property(s => s.DisplayName).Is(s => s.Name); public string DisplayName { get { return displayNameExpression.Evaluate(this); } } public string Name { get; set; } }
The “magic” happens inside of PropertyTranslator, when the interface type is automatically resolved to the class right before query execution: https://github.com/peschuster/PropertyTranslator/blob/master/src/PropertyTranslator/PropertyVisitor.cs#L57-66
LINQ: How to dynamically map properties | peschuster
[…] peschuster Technology, .NET and Web Skip to content HomeInfo ← How to add an uac shield icon to a MenuItem PropertyTranslator and Interfaces → […]