根据PropertyInfo名称

时间:2018-03-05 17:49:42

标签: c# linq extension-methods system.reflection

我正在尝试修改以下代码:

public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators, List<string> inTreatmentCohort)
{
    var type = typeof(T);
    var props = type.GetProperties();

    //Setup expression constants
    var param = Expression.Parameter(type, "x");
    var doublequote = Expression.Constant("\"");
    var doublequoteescape = Expression.Constant("\"\"");
    var comma = Expression.Constant(",");

    //Convert all properties to strings, escape and enclose in double quotes
    var propq = (from prop in props
        let tostringcall = Expression.Call(Expression.Property(param, prop),
            prop.ReflectedType.GetMethod("ToString", new Type[0]))
        let replacecall = Expression.Call(tostringcall,
            typeof(string).GetMethod("Replace", new[] {typeof(string), typeof(string)}), doublequote,
            doublequoteescape)
        select Expression.Call(
            typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
            doublequote, replacecall, doublequote)
    ).ToArray();

    var concatLine = propq[0];
    for (var i = 1; i < propq.Length; i++)
        concatLine =
            Expression.Call(
                typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
                concatLine, comma, propq[i]);

    var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
    var header = string.Join(",", props.Select(p => p.Name).ToArray());

    return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
}

我需要根据两个列表(keyIndi​​cators和inTreatmentCohort)进行过滤,这两个列表包含转换为CSV的列表中包含的PropertyInfo Name字段的后缀和前缀。

我尝试添加一个where keyIndi​​cators.Contains(prop.Name),基本上模拟一个返回null的IN语句。

我还尝试将propq查询放在foreach循环中,这会带来正确的数据,但显示的是所有列名,而不仅仅是在keyIndi​​cators或inTreatmentCohort列表中选择的列名。

如何修改此代码以仅返回包含两个过滤列表中的列的csv,而不是返回列表中的所有列?

修订以包含新的linq查询

修改了我之前提供的代码,包含现在按预期工作,这些更改可以在下面看到:

public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators,
    List<string> inTreatmentCohorts)
    {
        var type = typeof(T);
        var props = type.GetProperties();

        //Setup expression constants
        var param = Expression.Parameter(type, "x");
        var doublequote = Expression.Constant("\"");
        var doublequoteescape = Expression.Constant("\"\"");
        var comma = Expression.Constant(",");
        MethodCallExpression[] propq = { };
        var propqList = new List<MethodCallExpression>();

        //Convert all properties to strings, escape and enclose in double quotes


        foreach (var keyIndicator in keyIndicators)
        {
            if (keyIndicator != "Pend" && keyIndicator != "Area" && keyIndicator != "DrugGroup" &&
                keyIndicator != "Gender") continue;
            propq = (from prop in props
                let tostringcall = Expression.Call(Expression.Property(param, prop),
                    prop.ReflectedType.GetMethod("ToString", new Type[0]))
                let replacecall = Expression.Call(tostringcall,
                    typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }), doublequote,
                    doublequoteescape)
                where prop.Name.Contains(keyIndicator)
                select Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    doublequote, replacecall, doublequote)
            ).ToArray();

            propqList.AddRange(propq);
        }

        foreach (var keyIndicator in keyIndicators)
        {
            foreach (var inTreatmentCohort in inTreatmentCohorts)
            {
                propq = (from prop in props
                         let tostringcall = Expression.Call(Expression.Property(param, prop),
                             prop.ReflectedType.GetMethod("ToString", new Type[0]))
                         let replacecall = Expression.Call(tostringcall,
                             typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }),
                             doublequote,
                             doublequoteescape)
                         where prop.Name.Contains(inTreatmentCohort) && prop.Name.Contains(keyIndicator)
                         select Expression.Call(
                             typeof(string).GetMethod("Concat",
                                 new[] { typeof(string), typeof(string), typeof(string) }),
                             doublequote, replacecall, doublequote)
                ).ToArray();
            }

            propqList.AddRange(propq);
        }

        propq = propqList.ToArray();

        var concatLine = propq[0];
        for (var i = 1; i < propq.Length; i++)
            concatLine =
                Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    concatLine, comma, propq[i]);

        var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
        var header = string.Join(",", props.Select(p => p.Name).ToArray());

        return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
    }

我需要重写var头的LINQ查询,以便在生成csv时只显示在propq中选择的列。

2 个答案:

答案 0 :(得分:0)

在进行一些修改之后,我设法让Contains与几个foreach循环一起工作,以处理两个过滤器列表。

完整的代码如下所示:

public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators,
    List<string> inTreatmentCohorts)
    {
        var type = typeof(T);
        var props = type.GetProperties();

        //Setup expression constants
        var param = Expression.Parameter(type, "x");
        var doublequote = Expression.Constant("\"");
        var doublequoteescape = Expression.Constant("\"\"");
        var comma = Expression.Constant(",");
        MethodCallExpression[] propq = { };
        var propqList = new List<MethodCallExpression>();
        var columnNames = new List<string>();

        //Convert all properties to strings, escape and enclose in double quotes

        foreach (var keyIndicator in keyIndicators)
        {
            foreach (var inTreatmentCohort in inTreatmentCohorts)
            {
                propq = (from prop in props
                    let tostringcall = Expression.Call(Expression.Property(param, prop),
                        prop.ReflectedType.GetMethod("ToString", new Type[0]))
                    let replacecall = Expression.Call(tostringcall,
                        typeof(string).GetMethod("Replace", new[] {typeof(string), typeof(string)}), doublequote,
                        doublequoteescape)
                    where prop.Name.Contains(keyIndicator) && prop.Name.Contains(inTreatmentCohort)
                    select Expression.Call(
                        typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
                        doublequote, replacecall, doublequote)
                ).ToArray();

                var columnNameQuery = (from prop in props
                    where prop.Name.Contains(keyIndicator) && prop.Name.Contains(inTreatmentCohort)
                    select prop.Name);

                columnNames.AddRange(columnNameQuery);

                propqList.AddRange(propq);
            }
        }

        propq = propqList.ToArray();

        var concatLine = propq[0];
        for (var i = 1; i < propq.Length; i++)
            concatLine =
                Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    concatLine, comma, propq[i]);

        var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
        var header = string.Join(",", columnNames.ToArray());

        return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
    }

我想要包含在CSV中的列名称会添加到columnNames列表中,然后添加到标题变量中,以便列和数据在CSV中匹配。

答案 1 :(得分:-2)

请尝试以下操作:

            string[] columnNames = { "A", "B", "C", "D" };
            string[] filteredColumns = { "A", "C", "D" };

            string[] csv = {
                               "1,2,3,4",
                               "11,12,13,14",
                               "21,22,23,24",
                               "31,32,33,34"
                           };

            int[] indexes = columnNames.Select((x, i) => new { x = x, i = i }).Where(x => filteredColumns.Contains(x.x)).Select(x => x.i).ToArray();

            var results = csv.Select(x => x.Split(new char[] { ',' }).Where((y, i) => indexes.Contains(i)).ToArray()).ToArray();