将LINQ Join查询转换为DataTable

时间:2019-01-15 07:00:00

标签: c# asp.net linq datatable webforms

我想将LINQ Join查询结果转换为我已检查但找不到任何可靠解决方案的DataTable。

我尝试过两种方法 1:

var query = from A in ABC.AsEnumerable()
                        join X in XYZ.AsEnumerable()
                        on A.Field<int>("A-ID") equals
                        X.Field<int>("X-ID")
                        where ((A.Field<string>("A-Column1") == "1")
                        && (r.Field<string>("X-Column1") == "1"))
                        select new
                        {
                            UserName = ABC.Field<string>("UserName"),
                            UserExperience = XYZ.Field<string>("UserExperience"),
                            ...
                        };

2:

DataTable dt = new DataTable();
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("UserExperience", typeof(string));

var query = from A in ABC.AsEnumerable()
                        join X in XYZ.AsEnumerable()
                        on A.Field<int>("A-ID") equals
                        X.Field<int>("X-ID")
                        where ((A.Field<string>("A-Column1") == "1")
                        && (r.Field<string>("X-Column1") == "1"))
                        select dt.LoadDataRow(new object[]
                        {
                            ABC.Field<string>("UserName"),
                            XYZ.Field<string>("UserExperience"),
                            ...
                        }, false);

    DataTable ddt = new DataTable();

    ddt = query.CopyToDataTable();

但是,两者都无法解决我的问题。

我想将该结果转换为DataTable / DataSet。

先谢谢了。

1 个答案:

答案 0 :(得分:0)

创建以下方法并传递LINQ查询返回的任何类型的对象。

public static DataTable CreateDataTableFromAnyCollection<T>(IEnumerable<T> list)
    {
        Type type = typeof(T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity,null);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

并像这样传递您的LINQ结果

DataTable dt = CreateDataTableFromAnyCollection(list);

希望这会对您有所帮助。