簡體   English   中英

如何將LINQ查詢結果動態轉換為DataTable?

[英]How to convert a LINQ query result to a DataTable dynamically?

如何將LINQ查詢結果動態轉換為DataTable?

在解決方案中,您可以創建另一個類並指定列名稱,但是我希望能夠靈活地更改LINQ結構(例如列名稱,列數量),並使用列名稱自動生成DataTable。

謝謝

我已經包含了一個與SqlBulkCopy一起使用的擴展方法,該方法可以完成這項工作,但是我想問一下為什么要進行這種轉換。 在少數情況下(SqlBulkCopy是其中一種情況),對象列表無法完成數據表可以做的所有事情。 您可以將它們用作大多數控件的綁定源...很好奇。

public static DataTable toDataTable<T>(this IEnumerable<T> value, List<string> exclusionList)
        where T : class
    {
        var dataTable = new DataTable();

        var type = typeof(T);

        var properties = type.GetProperties().Where(x =>  !exclusionList.Contains(x.Name)).ToList();

        foreach (var propertyInfo in properties)
        {
            var propertyType = propertyInfo.PropertyType;
            if (!propertyType.IsScalar())
                continue;

            var nullableType = Nullable.GetUnderlyingType(propertyType);
            propertyType = nullableType ?? propertyType;

            var dataColumn = new DataColumn(propertyInfo.Name, propertyType);

            if (nullableType != null)
                dataColumn.AllowDBNull = true;

            dataTable.Columns.Add(dataColumn);
        }

        foreach (var row in value)
        {
            var dataRow = dataTable.NewRow();

            foreach (var property in properties)
            {
                var safeValue = property.GetValue(row, null) ?? DBNull.Value;                    
                dataRow[property.Name] = safeValue;
            }

            dataTable.Rows.Add(dataRow);
        }

        return dataTable;
    }

他們的關鍵是將LINQ查詢結果用作其Implemented IList接口。 如果您將結果作為方法的參數作為IList對象接收到,則可以通過以下方式訪問其列和行:

var props = item.GetType().GetProperties();

參考此示例,這是一個小類,請注意它只是抽象了DataTable的創建,並且內部應使用一個稱為“ LINQToDataTable”的靜態方法。

  1. 步驟1,創建一個名為“ GridHelper”的類(將System.Data用於DataTable結構)

     public class GridHelper { private DataTable baseDt; public GridHelper(string tableName) { baseDt = new DataTable(tableName); } public DataTable getDataTable() { return baseDt; } public object[,] getObjToFill() { object[,] obj = new object[baseDt.Columns.Count, 2]; for (int i = 0; i < baseDt.Columns.Count; i++) { obj[i, 0] = baseDt.Columns[i].ColumnName; } return obj; } public void addColumn(string colName, Type valueType) { baseDt.Columns.Add(colName, valueType); } public void addRow(object[,] values) { DataRow newRow = baseDt.NewRow(); for (int i = 0; i < values.Length / 2; i++) { bool colFound = false; for (int j = 0; j < baseDt.Columns.Count; j++) { if (baseDt.Columns[j].ColumnName == values[i, 0].ToString()) { colFound = true; break; } } if (colFound == false) { throw new Exception("The column " + values[i, 0].ToString() + " has not been added yet."); } newRow[values[i, 0].ToString()] = values[i, 1]; } baseDt.Rows.Add(newRow); } public static DataTable LINQToDataTable<T>(T objToList) where T : System.Collections.IList { GridHelper ghResult = new GridHelper("Report"); foreach (Object item in objToList) { var props = item.GetType().GetProperties(); foreach (var prop in props) { ghResult.addColumn(prop.Name, typeof(string)); //prop.Name //prop.GetValue(item) } break; } object[,] obj = ghResult.getObjToFill(); foreach (Object item in objToList) { var props = item.GetType().GetProperties(); int index = 0; foreach (var prop in props) { //ReportValue(prop.Name, prop.GetValue(item, null)); //prop.Name obj[index, 1] = prop.GetValue(item); index++; } ghResult.addRow(obj); } return ghResult.getDataTable(); } } 
  2. 用法:

      var listaReporte = (from t in dbContext.TablaPruebas select new { Name = t.name, Score = t.score } ) .ToList(); DataTable dt = Library.GridHelper.LINQToDataTable(listaReporte); 
  3. 也就是說,根據需要在GridView或DataGridView上使用DataTable

查看MoreLinq Nuget軟件包。 它具有函數ToDataTable()

var LinqResults = from ......;
DataTable dt_Results = LinqResults.ToDataTable();

https://code.google.com/p/morelinq/

它還具有其他非常有用的功能: https : //code.google.com/p/morelinq/wiki/Operators概述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM