首页 新闻 会员 周边

linq 查询list<datatable>如何返回datatable?

0
[已解决问题] 解决于 2015-08-07 12:00

linq 查询list<datable>中的数据如和才能返回一个datable,代码该怎么写啊?谢谢帮助,

c#
enhahaha的主页 enhahaha | 菜鸟二级 | 园豆:240
提问于:2015-08-03 21:10
< >
分享
最佳答案
1
public static DataTable ToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();
            // column names 
            PropertyInfo[] oProps = null;
            if (varlist == null)
                return dtReturn;
            foreach (T rec in varlist)
            {
                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;
        }
奖励园豆:5
稳稳的河 | 老鸟四级 |园豆:4216 | 2015-08-04 09:11

用扩展方法你当作LINQ一样的用吧

public static DataTable CopyToDataTable<T>(this IEnumerable<T> list)

{
var pList = new List<PropertyInfo>();
var type = typeof(T);
var dt = new DataTable();
Array.ForEach(type.GetProperties(), p =>
{
pList.Add(p);
dt.Columns.Add(p.Name);
});
foreach (var item in list)
{
DataRow row = dt.NewRow();
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
dt.Rows.Add(row);
}
return dt;
}

稳稳的河 | 园豆:4216 (老鸟四级) | 2015-08-04 09:28

谢谢,帮助。有点忙,结贴 结的有点晚,,

enhahaha | 园豆:240 (菜鸟二级) | 2015-08-07 12:02
其他回答(2)
0

first

吴瑞祥 | 园豆:29449 (高人七级) | 2015-08-03 21:31
0

return data[0];这种就是反回一个datatable吧。

list<string>怎么返回一个string?  list[1]这种就返回一个string了啊。

gw2010 | 园豆:1487 (小虾三级) | 2015-08-04 15:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册