2013-01-07 84 views
1

我有以下功能 -如何将var转换为DataTable?

public static DataTable getDetails(PersonContext context) 
{ 
DataTable dt = new DataTable(); 
IQueryable<Person> query = from p in context.Persons.Include("Employee") 
                .Include("Manager") 
                .Include("Activity") 
          where p.Activity.IsActive 
          select p; 
var sorted = query.ToArray().OrderByDescending(p=>p.Activity.DateCreated); 
dt = (DataTable)sorted; 
return dt; 
} 

我无法测试它。 我的问题是 - 这个功能会起作用吗?如果我不应该做什么改变?

更新

public static DataTable getDetails(PersonContext context) 
{ 
DataTable dt = new DataTable("Details"); 
dt.Columns.Add("Name"); 
dt.Columns.Add("Department"); 
dt.Columns.Add("IsManager"); 
IQueryable<Person> query = from p in context.Persons.Include("Employee") 
                .Include("Manager") 
                .Include("Activity") 
          where p.Activity.IsActive 
          select p; 
var sorted = query.ToArray().OrderByDescending(p=>p.Activity.DateCreated); 
foreach(Person p in sorted) 
{ 
    dt.Rows.Add(p.Name, p.Employee.Department,p.Manager.IsManager); 
} 
    return dt; 
} 
+1

找到更多的信息为什么你不能测试它? –

+1

就这样,这将不起作用,因为'sorted'将会正确输入'IQueryable '。我相信你应该在消费方面更好地排序结果,而不是在数据表本身内。排序是表示层的功能,而不是数据层 –

+0

检查这些解决方案[这里](http://www.dreamincode.net/forums/topic/85368-c%23-convert-object-array-into-datatable/)。 希望这会有所帮助。 –

回答

2
dt = (DataTable)sorted; 

是一个无效的转换。正确的方法是使用
dt.Rows.Add(query.ToArray().OrderByDescending(p=>p.Activity.DateCreated).toArray());将返回的数组添加到dt中。
你可以在Adding Data To Datatable

+0

谢谢@prthrokz。请参阅更新。现在这个工作吗? – RTRokzzz

+1

首先从Person创建一个DataRow。 DataRow dr = dt.NewRow();然后在该行添加必要的值,dr [“Name”] = p.Name; dr [“Dept”] = p.Employee.Department等。最后dt.Rows.Add(dr);所有这些都发生在foreach循环中。 – prthrokz

+0

谢谢@prthrokz。我遵循你的方式。但是,我无法测试它,但我认为,它现在可以工作。 – RTRokzzz

1

如果OrderByDescending返回类型为DataTable则不需要投。编译器在编译时知道方法返回类型的类型。

但是OrderByDescending不返回DataTable您需要构造它。