2012-04-28 7 views
42

Wie verwendet man in LINQ TO SQL union all. Ich habe den folgenden Code für die Union, dann wie man dies für die Union alle verwenden?Wie verwendet man Union alle in LINQ?

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

Sie sollten Jon Crowell Antwort markieren als ‚akzeptiert‘ – arviman

Antwort

87

Concat ist das Äquivalent von LINQ UNION ALL in SQL.

Ich habe ein einfaches Beispiel in LINQPad eingerichtet, um zu demonstrieren, wie man Union und Concat verwendet. Wenn Sie nicht LINQPad haben, holen Sie es.

Um unterschiedliche Ergebnisse für diese Mengenoperationen anzeigen zu können, müssen die ersten und zweiten Datenmengen mindestens eine gewisse Überlappung aufweisen. Im folgenden Beispiel enthalten beide Sätze das Wort "nicht".

Öffnen Sie LINQPad und legen Sie das Dropdown-Menü Sprache auf C# -Anweisung (en) fest. Fügen Sie den folgenden in den Abfragebereich und führen Sie es:

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... 

Das Ergebnis in LinqPad sieht wie folgt aus:

enter image description here