How to create a dynamic LINQ select projection function from a string[] of names?

后端 未结 1 1817
你的背包
你的背包 2020-12-30 08:11

Using C#...

Is there any way to specify property names for a projection function on a LINQ select method, from an array.

public class          


        
1条回答
  •  醉梦人生
    2020-12-30 08:30

    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));
    //...
    

    0 讨论(0)
提交回复
热议问题