1

我正在尝试使用 linq 加入两个数据表

var invoices420 = dt420_.AsEnumerable();
var invoices430 = dt430_.AsEnumerable();

            var query = from inv430 in invoices430
                        join inv420 in invoices420 on inv430.LinkDoc equals inv420.LinkDoc
                        orderby inv430.SID
                        select new
                {
                    LinkDoc = inv430.LinkDoc,
                    TotalIn = Math.Round(inv430.Credit, 2),
                    TotalOut = ((inv420 == null) ? 0 : Math.Round(inv420.Debit, 2))

                };

加入似乎不是问题,但我收到错误“System.Data.DataRow”不包含“LinkDoc”的定义,并且没有扩展方法“LinkDoc”接受“System.Data.DataRow”类型的第一个参数' 可以找到(您是否缺少 using 指令或程序集引用?)。

在不使用 inv430.Field("linkdoc") 的情况下,我必须做什么才能引用 DataTable 中的列,例如 inv430.LinkDoc?

如果我想对结果集进行分组,我在想

var q2 = query
         .GroupBy(item => item.LinkDoc);

return q2.ToArray();

问题是在第二季度我没有得到所有的列(linkdoc、totalin、totalout)。

原始数据是

dt420_
Linkdoc   Credit
Invoice1  500
Invoice2  100
Invoice3  200

dt430_
LinkDoc   Debit
Invoice1  100
Invoice1  100
Invoice2  200

Result would be
LinkDoc    TotalIn(Credit)  TotalOut(Debit)
Invoice1   500              200
Invoice2   100              200
Invoice3   200              0
4

1 回答 1

1

您需要将所有直接调用的位置替换为属性,例如

inv430.LinkDoc

inv430["LinkDoc"]

inv430 是一个DataRow所以你需要使用获取字符串的索引器。

编辑:您的加入会带来错误的数据(请参阅下面的评论)。您需要使用以下代码:

var group430 = from inv430 in invoices430
               group inv430 by inv430["LinkDoc"].ToString().Trim() into g
               select new
               {
                    LinkDoc = g.Key.ToString().Trim(),
                    TotalOut = g.Sum(inv => Math.Round((decimal)inv["Debit"], 2))
               };

var group420 = from inv420 in invoices420
               group inv420 by inv420["LinkDoc"].ToString().Trim() into g
               select new
               {
                    LinkDoc = g.Key.ToString().Trim(),
                    TotalIn = g.Sum(inv => Math.Round((decimal)inv["Credit"], 2))
               };

var result = from inv430 in group430
             join inv420 in group420 on inv430.LinkDoc equals inv420.LinkDoc into inv
             from inv420 in inv.DefaultIfEmpty()
             select new
             {
                 inv430.LinkDoc,
                 TotalOut = inv430.TotalOut,
                 TotalIn = inv420 != null ? inv420.TotalIn : 0
             };
于 2012-11-11T09:38:54.647 回答