如何查询内存中的DataTable以填充另一个数据表

我正在尝试更新Microsoft报告。 它的作用是写出从转换过程中排除的客户数量以及原因。 目前,程序将所有已删除的客户端写回服务器,然后将其查询回来以填充包含结果的专业表。

这是当前的查询:

SELECT DeletedClients.Reason, COUNT(DeletedClients.Reason) AS Number, CAST(CAST(COUNT(DeletedClients.Reason) AS float) / CAST(t.Total AS float) * 100 AS numeric(4, 1)) AS percentage FROM DeletedClients CROSS JOIN (SELECT COUNT(*) AS Total FROM DeletedClients AS DeletedClients_1 WHERE (ClinicID = @ClinicID)) AS t WHERE (DeletedClients.ClinicID = @ClinicID) AND (DeletedClients.TotalsIdent = @ident) GROUP BY DeletedClients.Reason, t.Total ORDER BY Number DESC 

我想做的是不将DeletedClients写入服务器,因为它已作为DataTable存在于我的程序的内存中,它只会减慢报告速度并使用我们不需要保存的信息填充数据库。

我的主要问题是,要么:

如何查询数据表以创建一个新的内存数据表,其结果与我写出SQL服务器并使用上面的查询读回来的结果相同?

要么

如何在Microsoft Reports中为Tablix中的项目执行group by子句=Fields!Reason.Value =Fields!Number.Value =Fields!percentage.Value类似于上面查询返回的结果?

您可以使用DataTable.Select查询DataTable。

 DataTable table = GetDataTableResults(); DataTable results = table.Select("SomeIntColumn > 0").CopyToDataTable(); 

或者对于更复杂的查询,您可以使用LINQ查询DataTable:

 DataTable dt = GetDataTableResults(); var results = from row in dt.AsEnumerable() group row by new { SomeIDColumn = row.Field("SomeIDColumn") } into rowgroup select new { SomeID = rowgroup.Key.SomeIDColumn, SomeTotal = rowgroup.Sum(r => r.Field("SomeDecimalColumn")) }; DataTable queryResults = new DataTable(); foreach (var result in query) queryResults.Rows.Add(new object[] { result.SomeID, result.SomeTotal }); 

我可以通过两种方式来查询数据表。 以下是使用两种方式的示例。

 using System; using System.Data; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main() { var deletedClients = GetDataTable(); // Using linq to create the new DataTable. var example1 = deletedClients.AsEnumerable() .Where(x => x.Field("ClinicId") == 1) .CopyToDataTable(); // Using the DefaultView RowFilter to create a new DataTable. deletedClients.DefaultView.RowFilter = "ClinicId = 1"; var rowFilterExample = deletedClients.DefaultView.ToTable(); } static DataTable GetDataTable() { var dataTable = new DataTable(); // Assumes ClinicId is an int... dataTable.Columns.Add("ClinicId", typeof(int)); dataTable.Columns.Add("Reason"); dataTable.Columns.Add("Number", typeof(int)); dataTable.Columns.Add("Percentage", typeof(float)); for (int counter = 0; counter < 10; counter++) { dataTable.Rows.Add(counter, "Reason" + counter, counter, counter); } return dataTable; } } }