66

如何在 LINQ TO SQL 中使用 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();
4

1 回答 1

125

ConcatUNION ALLSQL 中的 LINQ 等价物。

我在 LINQPad 中设置了一个简单的示例来演示如何使用UnionConcat. 如果您没有LINQPad,请获取它。

为了能够看到这些集合操作的不同结果,第一组和第二组数据必须至少有一些重叠。在下面的示例中,两个集合都包含单词“not”。

打开 LINQPad 并将 Language 下拉菜单设置为 C# Statement(s)。将以下内容粘贴到查询窗格中并运行它:

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 中的结果如下所示:

在此处输入图像描述

于 2012-04-28T04:20:25.913 回答