用LINQ - Join 2个数据表动态选择语句

本文关键字:动态 选择 语句 数据表 2个 LINQ Join | 更新日期: 2023-09-27 18:15:47

我有一个问题,当我试图在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的错误:

(局部变量)string选择字符串错误:

方法"System.Linq.Enumerable.Select(System.Collections.Generic. select)"的类型参数。IEnumerable, System.Func)'不能从用法中推断出来。尝试指定显式地键入参数

似乎问题直接出在额外的类上。

用LINQ - Join 2个数据表动态选择语句

我找到了一个使用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共享这段代码