Can I create an extension method to return a single property or field to a list of objects?
I currently have many features, such as:
public static List<int> GetSpeeds(this List<ObjectMotion> motions) {
List<int> speeds = new List<int>();
foreach (ObjectMotion motion in motions) {
speeds.Add(motion.Speed);
}
return speeds;
}
This is hardcoded and serves only one property in one type of object. This is tiring, and I'm sure there is a way to use LINQ / Reflection to create an extension method that can do this in a universal and reusable way. Something like that:
public static List<TProp> GetProperties<T, TProp>(this List<T> objects, Property prop){
List<TProp> props = new List<TProp>();
foreach (ObjectMotion obj in objects) {
props.Add(obj.prop??);
}
return props;
}
Besides the simplest method using LINQ, I am also looking for the fastest method. Is it possible to use code generation (and Lambda expression trees) to create such a method at runtime? I am sure it will be faster than using Reflection.
source