构建动态linq Func以返回字符串

时间:2016-05-10 10:57:05

标签: c# linq dynamic linq-to-entities

我正在试图找出一个IQueryable如何通过动态选择对象作为字符串来构建csv文件。

例如:

我读到这个关于动态选择T ...

的属性的内容

LINQ : Dynamic select

这会让我做这样的事情......

var data = new List<T> { items };
            var fields = new string[] { "Field1", "Field2", "Field3" };
            // build row strings
            var rows = set.Select(BuildRowObjectExpression<T, ProjectionOfT>(fields))
                .Select(i => Serialise<ProjectionOfT>(i));


        string Serialise<T>(T i, string separator)
        {
            var properties = typeof(T).GetProperties();
            var values = new List<string>();
            foreach (var p in properties)
                values.Add(p.GetValue(i).ToString());

            return string.Join(separator, values);
        }

        Func<T, Tout> BuildRowObjectExpression<T, Tout>(string[] fields)
        {
            // input parameter "o"
            var xParameter = Expression.Parameter(typeof(T), "o");

            // new statement "new Data()"
            var xNew = Expression.New(typeof(T));

            // create initializers
            var bindings = fields.Select(o => {

                    // property "Field1"
                    var mi = typeof(T).GetProperty(o);

                    // original value "o.Field1"
                    var xOriginal = Expression.Property(xParameter, mi);

                    // set value "Field1 = o.Field1"
                    return Expression.Bind(mi, xOriginal);
                }
            );

            // initialization "new T { Field1 = o.Field1, Field2 = o.Field2 }"
            var xInit = Expression.MemberInit(xNew, bindings);

            // expression "o => new T { Field1 = o.Field1, Field2 = o.Field2 }"
            var lambda = Expression.Lambda<Func<T, string>>(xInit, xParameter);

            // compile to Func<T, string>
            return lambda.Compile();
        }

但我想知道的是:

如何将其构建为表达式/ func,我可以使用IQueryable来执行此类操作

// this would build me a string array from the specified properties 
// in a collection of T joining the values using the given separator 
var results = data.Select(i => BuildString(fields, "|")).ToArray();

我希望将它与实体集一起使用。

1 个答案:

答案 0 :(得分:0)

字符串转换/连接不是数据库作业。您最好将这两部分分开 - 数据库查询中的数据检索和内存查询中的数据转换。

例如,您可以使用以下自定义扩展方法:

public static class Extensions
{
    public static IQueryable<T> Select<T>(this IQueryable source, string[] fields)
    {
        var parameter = Expression.Parameter(source.ElementType, "o");
        var body = Expression.MemberInit(
            Expression.New(typeof(T)),
            fields.Select(field => Expression.Bind(
                typeof(T).GetProperty(field),
                Expression.PropertyOrField(parameter, field))
            )
        );
        var selector = Expression.Lambda(body, parameter);
        var expression = Expression.Call(
            typeof(Queryable), "Select", new[] { parameter.Type, body.Type },
            source.Expression, Expression.Quote(selector)
        );
        return source.Provider.CreateQuery<T>(expression);
    }

    public static IEnumerable<string> Serialize<T>(this IEnumerable<T> source, string separator)
    {
        var properties = typeof(T).GetProperties();
        return source.Select(item => string.Join(separator, properties.Select(property => property.GetValue(item))));
    }
}
像这样

var results = db.Data.Select<ProjectionOfT>(fields).Serialize("|");

如果你想避免使用ProjectionOfT类,那么就没有简单的方法可以做到这一点,因为它需要动态的运行时类生成,因此你最好使用System.Linq.Dynamic包。

相关问题