0

在我的代码中,我得到了需要将查询列表转换为表格的实例。我使用以下方法来实现这一点:

//Attach query results to DataTables
    public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
    {
        DataTable dtReturn = new DataTable();

        // column names 
        PropertyInfo[] oProps = null;

        if (varlist == null) return dtReturn;

        foreach (T rec in varlist)
        {
            // Use reflection to get property names, to create table, Only first time, others will follow 
            if (oProps == null)
            {
                oProps = ((Type)rec.GetType()).GetProperties();
                foreach (PropertyInfo pi in oProps)
                {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                    == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }

                    dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                }
            }

            DataRow dr = dtReturn.NewRow();

            foreach (PropertyInfo pi in oProps)
            {
                dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                (rec, null);
            }

            dtReturn.Rows.Add(dr);
        }
        return dtReturn;
    }

它完美地工作,在下面的例子中:

DataTable gridTable = LINQToDataTable(GetGrids); // Loads Query into Table

而不是在各种 .cs 文件中复制该方法 - 如果它是它自己的实用程序类,它将允许我编写如下内容:

DataTable gridTable = Utility.LINQToDataTable(GetGrids); // Loads Query into Table

以免重复多次??

4

2 回答 2

1

将您的方法移动到Utility调用并使其成为static

public class Utility
{
   public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
   {
      // code ....
   }

}

现在您可以将其称为:

DataTable gridTable = Utility.LINQToDataTable(GetGrids); 
于 2013-08-21T02:15:04.840 回答
1
public static class EnumerableExtensions
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
    {
        // .. existing code here ..
    }
}

按如下方式使用它:

GetGrids.ToDataTable();
// just like the others
GetGrids.ToList();
于 2013-08-21T02:22:42.197 回答