How to Convert var to DataTable?

asp.net c# entity-framework linq

Question

I have following function -

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;
}

I can't test it. My question is - will this function work. If no what changes should I make in it?

Update

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
1/7/2013 9:54:56 AM

Accepted Answer

dt = (DataTable)sorted;

is an invalid cast. The correct way is to add the returned array to dt using
dt.Rows.Add(query.ToArray().OrderByDescending(p=>p.Activity.DateCreated).toArray());.
You can find more information at Adding Data To Datatable

2
1/7/2013 9:06:20 AM

Popular Answer

OrderByDescending() returns an IEnumerable not a DataTable

This link answers what seems to be the same question. LINQ to DataTable Easy and Fast



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow