Comment utiliser union all dans LINQ?

Comment utiliser union all dans LINQ to SQL. J'ai utilisé le code suivant pour union, alors comment l'utiliser pour 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();
48
demandé sur Jon Crowell 2012-04-28 08:14:53

1 réponses

Concat est L'équivalent LINQ de UNION ALL en SQL.

J'ai mis en place un exemple simple dans LINQPad pour démontrer comment utiliser Union et Concat. Si vous n'avez pas LINQPad , obtenez-le.

Afin de pouvoir voir des résultats différents pour ces opérations d'ensemble, les premier et deuxième ensembles de données doivent avoir au moins un certain chevauchement. Dans l'exemple ci-dessous, les deux ensembles contiennent le mot "pas".

Ouvrez LINQPad et définissez la liste déroulante de langue sur C# instruction (S). Collez ce qui suit dans le volet de requête et exécutez-le:

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

Le résultat dans LinqPad ressemble à ceci:

entrez la description de l'image ici

95
répondu Jon Crowell 2016-10-07 12:03:56