C# 如何将 var 转换为 DataTable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14192611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:00:47  来源:igfitidea点击:

How to Convert var to DataTable?

c#asp.netlinqentity-framework

提问by RTRokzzz

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

采纳答案by prthrokz

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

是无效演员表。正确的方法是使用 将返回的数组添加到 dt
dt.Rows.Add(query.ToArray().OrderByDescending(p=>p.Activity.DateCreated).toArray());
您可以在将数据添加到数据表中找到更多信息

回答by MBen

If the return type of OrderByDescendingwasDataTablethen the cast is not needed. The compiler knows the type of the method return type at compile time.

如果返回类型OrderByDescending是,DataTable则不需要强制转换。编译器在编译时知道方法返回类型的类型。

However OrderByDescendingdoesn't return a DataTableYou need to construct it.

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

回答by Moriya

OrderByDescending() returns an IEnumerable not a DataTable

OrderByDescending() 返回一个 IEnumerable 而不是 DataTable

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

此链接回答了似乎是同一个问题。 LINQ to DataTable 简单快速