2012-11-11 65 views
1
參考數據表列

我試圖使用LINQ使用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)) 

       }; 

加入似乎並不成爲一個問題連接兩個數據表,但我得到一個error'System.Data.DataRow」不包含定義爲'LinkDoc'並且沒有擴展方法'LinkDoc'接受類型'System.Data.DataRow'的第一個參數可以找到(你是否缺少using指令或程序集引用?)。

如何在DataTable中引用列,例如inv430.LinkDoc而不使用inv430.Field(「linkdoc」)?

如果我想通過對結果集我想

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

return q2.ToArray(); 

問題做一組是在Q2我不明白的所有列(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 

回答

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

好的,這是有道理的。加入兩個數據表時可以使用group嗎? – mko

+0

您可以使用group by作爲任何可枚舉的 –

+0

,但它必須分組在一個單獨的操作中? – mko