Reputation: 2613
Is there a Linq equivalent for the following piece of code where Properties
is a list of properties in the object T and entry
is an instance of T.
I find that I do code like this ever so often and I Was wondering if there was a more simple clear way to do this using linq.
List<Object> args = new List<Object>();
for (int i = 0; i < Properties.Count; i++)
args.Add(typeof(T).GetProperty(Properties[i]).GetValue(entry));
Upvotes: 0
Views: 78
Reputation: 35891
This should be the equivalent, using the Select
method:
var args = Properties
.Select(p => typeof(T).GetProperty(p))
.Select(p => p.GetValue(entry))
.ToList();
You can of course have the whole typeof(T).GetProperty(p).GetValue(entry)
part in one Select
- I've split it for clarity. Note that it doesn't make much difference in terms of memory/performance - it won't create any additional collection in between, because LINQ is lazily evaluated, and it won't "run" until the ToList
call.
Upvotes: 1
Reputation: 60503
Properties.Select(t => typeof(T).GetProperty(t).GetValue(entry)).ToList();
now if you use often, just create an extension method (in a static helper class)
public static IList<object> GetValuesFor<T>(this IEnumerable<string> properties, T instance) {
return properties.Select(t => typeof(T).GetProperty(t).GetValue(instance)).ToList();
}
and usage
var args = Properties.GetValuesFor(entry);
Upvotes: 1
Reputation: 73482
var args = Properties
.Select(x=> typeof(T).GetProperty(x).GetValue(entry))
.ToList();
Upvotes: 1
Reputation: 13104
You are transforming properties into values, which means that you can use the Select
method:
var args = Properies.Select( p => typeof(T).GetProperty(p).GetValue(entry) );
Upvotes: 1