Using C#...
Is there any way to specify property names for a projection function on a LINQ
select method, from an array.
public class
You could use reflection and dynamic types to generate an object with only the specified fields/properties.
Below is a simple way of doing this. You can do optimizations, like having a type cache for the reflection. But this should work for simple fields/properties.
public static object DynamicProjection(object input, IEnumerable properties)
{
var type = input.GetType();
dynamic dObject = new ExpandoObject();
var dDict = dObject as IDictionary;
foreach (var p in properties)
{
var field = type.GetField(p);
if (field != null)
dDict [p] = field.GetValue(input);
var prop = type.GetProperty(p);
if (prop != null && prop.GetIndexParameters().Length == 0)
dDict[p] = prop.GetValue(input, null);
}
return dObject;
}
Usage:
//...
var names = new[] { "Id", "Name", "Tracks" };
var projection = collection.Select(x => DynamicProjection(x, names));
//...