Linq DataTable有查询

时间:2012-09-10 18:27:26

标签: c# linq datatable

我使用Microsoft.ACE.OLEDB驱动程序查询excel文件。然后将结果传递给DataTAble。但是,此驱动程序不支持我想使用的T-SQL查询。

with abc as
(
SELECT Credit, Debit,[Reference 2] As [Job Code]
from xlSheet
WHERE ([Reference 2] LIKE '%JOB%') OR ([Reference 2] LIKE '%CRN%')
union all
SELECT Credit, Debit,[Reference] As [Job Code]
from xlSheet
WHERE ([Reference] LIKE '%JOB%') OR ([Reference] LIKE '%CRN%')
)
SELECT sum(Credit) as  Credit, sum(debit) as Debit,ABS(ROUND(SUM(Debit - Credit),2)) as Total , [Job Code],
            case when ROUND(SUM(Debit - Credit),2) < 0
                then 'JOB'
                else 'JOBR'
            end as 'Trans Code' 
from abc
group by [Job Code]
HAVING ROUND(SUM(debit - credit),2)  <> 0

所以,我把它分成两个查询即:

SELECT Credit, Debit,[Reference 2] As [Job Code]
    from xlSheet
    WHERE ([Reference 2] LIKE '%JOB%') OR ([Reference 2] LIKE '%CRN%')
    union all
    SELECT Credit, Debit,[Reference] As [Job Code]
    from xlSheet
    WHERE ([Reference] LIKE '%JOB%') OR ([Reference] LIKE '%CRN%')

还有第二个:

SELECT sum(Credit) as  Credit, sum(debit) as Debit,ABS(ROUND(SUM(Debit - Credit),2)) as Total , [Job Code], 
            case when ROUND(SUM(Debit - Credit),2) < 0 
                then 'JOB' 
                else 'JOBR' 
            end as 'Trans Code'  
from abc 
group by [Job Code] 
HAVING ROUND(SUM(debit - credit),2)  <> 0 

现在我知道可以在DataTable上执行基本的选择查询,但没有这么复杂。我听说过LINQ,我相信这可以通过这个来完成。 但是对LINQ不熟悉我在这方面需要一些帮助。 如果做不到这一点,我看到的唯一另一种方法是将结果写回辅助excel文件,并使用辅助查询重新读取文件 - 但这会产生巨大的性能缺陷。

2 个答案:

答案 0 :(得分:1)

如果您需要开始使用,我们有LINQ in Action的免费章节介绍LINQ和第14章讨论LINQ to DataSets(您将用于DataTables)。您可以在http://www.manning.com/marguerie/阅读它们。

答案 1 :(得分:0)

所以我使用Linq到DataTable解决了我的查询,如下所示:

        var result = from b in dsXLData.Tables[0].AsEnumerable()
                     group b by b.Field<string>("cJobCode")  into grp
                     where grp.Sum(e => Math.Round(e.Field<Double>("debit"),2) - Math.Round(e.Field<Double>("credit"),2)) != 0
                     select new
                     {
                         cJobCode = grp.Key,
                         Credit = Math.Round(grp.Sum(x => x.Field<Double>("credit")), 2),
                         Debit = Math.Round(grp.Sum(x => x.Field<Double>("debit")), 2),
                         Amount_Incl = Math.Round(Math.Abs(grp.Sum(x => x.Field<Double>("debit")) - grp.Sum(x => x.Field<Double>("credit"))), 2),
                         Trans_Code =
                                (
                                    Math.Round(grp.Sum(x => x.Field<Double>("debit")) - grp.Sum(x => x.Field<Double>("credit")), 2) < 0 ? "JOB" : "JOBR"
                                )

                     };