如何从名称的string []创建动态LINQ select投影函数? [英] How to create a dynamic LINQ select projection function from a string[] of names?

查看:56
本文介绍了如何从名称的string []创建动态LINQ select投影函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#...

有什么方法可以从数组中为LINQ选择方法上的投影函数指定属性名称.

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

public class Album
{
    public int Id { get; set; }
    public string Name { get; set; }
    public short Rate { get; set; }
    public string Genre { get; set; }
    public short Tracks { get; set; }
}

public class Class1
{
    private void Some<T>()
    {
        // Example of source
        var names = new[] { "Id", "Name", "Tracks" };

        var query = myDataContext.
                    GetTable<T>.
                    AsQueryable().
                    Select( /* dynamic projection from names array */ );

                    // something like
                    // Select(x => new
                    //     {
                    //         x.Id,
                    //         x.Name,
                    //         x.Tracks
                    //     }

        GoAndDoSomethingWith(query);
    }
}

可以在没有System.Linq.Dynamic的情况下完成此操作吗?

Could this be done without System.Linq.Dynamic?

推荐答案

您可以使用反射和动态类型来生成仅具有指定字段/属性的对象.

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<string> properties)
{
    var type = input.GetType();
    dynamic dObject = new ExpandoObject();
    var dDict = dObject as IDictionary<string, object>;

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

用法:

//...
var names = new[] { "Id", "Name", "Tracks" };
var projection = collection.Select(x => DynamicProjection(x, names));
//...

这篇关于如何从名称的string []创建动态LINQ select投影函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆