How to collect one property in the list of objects?

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.

+5
source
3

:

public static List<TProp> GetProperties<T, TProp>(this IEnumerable<T> seq, Func<T, TProp> selector)
{
    return seq.Select(selector).ToList();
}

:

List<int> speeds = motions.GetProperties(m => m.Speed);

, , Select ToList .

+7

:

List<int> values = motions.Select(m=>m.Speed).ToList();
+5

A for the loop will be the fastest, I think, I carefully monitor linq (minimum overhead if you do not use closure). I can’t imagine that any other mechanism would be better than this.

You can replace List<int>with int[]or initialize the list with a specific capacity. This will probably do more to speed up your code than anything else (although still not so much).

+1
source

All Articles