Aelphaeis
Aelphaeis

Reputation: 2613

Is there a Linq equivalent for creating collection from subset of an object used in a previous collection

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

Answers (4)

BartoszKP
BartoszKP

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

Rapha&#235;l Althaus
Rapha&#235;l Althaus

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

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

var args = Properties
           .Select(x=> typeof(T).GetProperty(x).GetValue(entry))
           .ToList();

Upvotes: 1

Chris Pitman
Chris Pitman

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

Related Questions