2012-04-28 103 views
42

如何在LINQ TO SQL中使用union all。 我已經使用以下代碼進行聯合,那麼如何將這個用於union all?如何在LINQ中使用union all?

List<tbEmployee> lstTbEmployee = obj.tbEmployees.ToList(); 
List<tbEmployee2> lstTbEmployee2 = (from a in lstTbEmployee 
            select new tbEmployee2 
            { 
             eid = a.eid, 
             ename = a.ename, 
             age = a.age, 
             dept = a.dept, 
             doj = a.doj, 
             dor = a.dor 

            }).Union(obj.tbEmployee2s).ToList(); 
+3

你應該慶祝喬恩·韋爾的答案爲「接受」 – arviman 2014-06-09 08:07:44

回答

87

Concat是SQL中UNION ALL的LINQ等效項。

我在LINQPad中設置了一個簡單的例子來演示如何使用UnionConcat。如果你沒有LINQPad,就明白吧。

爲了能夠看到這些設置操作的不同結果,第一組和第二組數據必須至少有一些重疊。在下面的例子中,兩組都包含單詞「不」。

打開LINQPad並將語言下拉菜單設置爲C#語句。以下內容粘貼到查詢窗格中並運行它:

string[] jedi = { "These", "are", "not" }; 
string[] mindtrick = { "not", "the", "droids..." }; 

// Union of jedi with mindtrick 
var union = 
    (from word in jedi select word).Union 
    (from word in mindtrick select word); 

// Print each word in union 
union.Dump("Union"); 
// Result: (Note that "not" only appears once) 
// These are not the droids... 

// Concat of jedi with mindtrick (equivalent of UNION ALL) 
var unionAll = 
    (from word in jedi select word).Concat 
    (from word in mindtrick select word); 

// Print each word in unionAll 
unionAll.Dump("Concat"); 
// Result: (Note that "not" appears twice; once from each dataset) 
// These are not not the droids... 

// Note that union is the equivalent of .Concat.Distinct 
var concatDistinct = 
    (from word in jedi select word).Concat 
    (from word in mindtrick select word).Distinct(); 

// Print each word in concatDistinct 
concatDistinct.Dump("Concat.Distinct"); 
// Result: (same as Union; "not" only appears once) 
// These are not the droids... 

在LinqPad結果看起來是這樣的:

enter image description here