使用LINQ动态选择句子 - 加入2个DataTables

时间:2014-07-30 19:40:46

标签: c# linq lambda

当我尝试在LINQ中生成通用选择语句时,我遇到了一个与Visual Studio相关的问题

主要代码:

private void DynamicLinq()
{
    DataTable Table1 = new DataTable();
    DataTable Table2 = new DataTable();

    // CREATE COLUMNS AND FILL THE DATATABLES

    string SelectString = "a.Amount, b.User"; // Generic selection of fields

    var vLINQ = (from a in Table1.AsEnumerable()
                 join b in Table2.AsEnumerable()
                 on a.Field<Object>("ID") equals b.Field<Object>("ID")
                 into Group
                 from q in Group.DefaultIfEmpty()
                 select q).Select(SelectString);
}

这是项目的附加类:

public class SelectBuilder<T, T>
{
    Func<T, T> CreateNewStatement(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.Split(',').Select(o => o.Trim())
            .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 (MemberBinding)Expression.Bind(mi, xOriginal);
            }
        );

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

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

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

这是向我展示VisualStudio的错误:

  

(局部变量)字符串SelectString   错误:

     

方法&#39; System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)&#39;的类型参数。无法从使用中推断出来。尝试指定   明确地输入参数。

似乎问题直接来自附加类。

1 个答案:

答案 0 :(得分:0)

我找到了DynamicLinq实施的解决方法:

IQueryable linqData = (from row1 in dtMain.AsEnumerable()
                       join row2 in dtSec.AsEnumerable()
                       on row1.Field<Object>("frameworkIdTemporal1") equals row2.Field<Object>("frameworkIdTemporalSec1")
                       into result
                       from subRight in result.DefaultIfEmpty()
                       select
                       new { row1, row3 = (subRight == null) ? (dtSec.NewRow()) : subRight })
                       .AsQueryable().Select(strSelect); 

我与LINQ

共享代码片段