6

Is it possible to create an extension method to return a single property or field in a list of objects?

Currently I have a lot of functions like the following.

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 "hard coded" and only serves a single property in a single object type. Its tedious and I'm sure there's a way using LINQ / Reflection to create an extension method that can do this in a generic and reusable way. Something like this:

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;
}

Apart from the easiest method using LINQ, I'm 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'm sure that would be faster than using Reflection.

2
  • You function could be written as "motions.Select( motion => motion.Speed)". That's not exactly generic, but for a start it's a lot shorter than writing and calling a method each time. Commented Mar 12, 2013 at 13:58
  • Only calling my method may be faster. (LINQ is usually slower than non-generic code) Commented Mar 12, 2013 at 13:58

3 Answers 3

7

You could do:

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

and use it like:

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

it's questionable whether this method is better than just using Select and ToList directly though.

Sign up to request clarification or add additional context in comments.

Comments

7

It is, no reflection needed:

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

3 Comments

How do I create an extension method to do this? I don't want to write this snippet everytime. And how do I use code generation to create the fastest method?
public static List<O> GetValues<T,O>(this List<T> target, Func<T,O> selector){ return target.Select(selectoror);}
but no need to make a function, Select is a function already
1

A for loop would be the fastest I think, followed closely by linq (minimal overhead if you don't do use closures). I can't image any other mechanism would be any better than that.

You could replace the List<int> with a int[] or initialize the list with a certain capacity. That would probably do more to speed up your code than anything else (though still not much).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.