2013-08-29 64 views
2

我有一個方法使用LINQ在兩個DataTable上執行不匹配的查詢。它產生了一個錯誤,通過在網上查找我已經確定了我認爲發生錯誤的位置,但我無法弄清楚如何解決它。顯式轉換的IEnumerable <AnonymousType#1>

public IEnumerable<int> UnbilledAuditKeys(DataTable audits, string keyFieldName) { 
    var billedAudits = 
     from x in this.GetBilledAudits().AsEnumerable() 
     select new { 
      k = x.Field<int>(keyFieldName) 
     }; 

    var allAudits = 
     from x in audits.AsEnumerable() 
     select new { 
      k = x.Field<int>(keyFieldName) 
     }; 

    var unbilled = 
     from a in allAudits 
     join b in billedAudits on a.k equals b.k 
      into combined 
     from c in combined.DefaultIfEmpty() 
     where c == null 
     select new { // This is what's causing the error (I think) 
      k = a.k 
     }; 

    return unbilled; // This line the compiler is rejecting 
} 

返回的錯誤是

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<int>'. An explicit conversion exists (are you missing a cast?) 

我在如何解決它的損失。我已經嘗試了將整個LINQ表達式轉換爲IEnumerable,但會產生運行時異常。

任何想法將不勝感激!

編輯:

的最後一個方法:

public IEnumerable<int> UnbilledAuditKeys(DataTable rosliAudits, string keyFieldName) { 
    var billed = this.GetBilledAudits().AsEnumerable().Select(x => x.Field<int>(keyFieldName)); 
    var allaudits = rosliAudits.AsEnumerable().Select(x => x.Field<int>(keyFieldName)); 
    var unbilled = allaudits.Except(billed); 
    return unbilled; 
} 

回答

3

簡單的解決方法:

var unbilled = 
    from a in allAudits 
    join b in billedAudits on a.k equals b.k 
     into combined 
    from c in combined.DefaultIfEmpty() 
    where c == null 
    select a.k; 

而且,o其中兩個查詢似乎並不需要匿名結構,最後一個可以被極大地簡化:

public IEnumerable<int> UnbilledAuditKeys(DataTable audits, string keyFieldName) { 
    var billedAudits = 
     from x in this.GetBilledAudits().AsEnumerable() 
     select x.Field<int>(keyFieldName); 

    var allAudits = 
     from x in audits.AsEnumerable() 
     select x.Field<int>(keyFieldName); 

    var unbilled = allAudits.Except(billedAudits); // LINQ has many useful methods like this 

    return unbilled; 
} 
+0

我愛LINQ !!!但我對它很新,以至於我仍然把它當作SQL來對待。非常感謝!這工作完美:) –

2

選擇你的領域,而不是直接創造新的匿名類型:

var unbilled = 
    from a in allAudits 
    join b in billedAudits on a.k equals b.k 
     into combined 
    from c in combined.DefaultIfEmpty() 
    where c == null 
    select a.k; 
+0

這也適用! –

相關問題