如何在LINQ中使用Union All? [英] How to use union all in LINQ?
问题描述
如何在LINQ TO SQL中使用并集. 我将以下代码用于联合,然后如何将其用于所有联合?
How to use union all in LINQ TO SQL. I have use the following code for union, then how to use this for 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();
推荐答案
Concat
是SQL中UNION ALL
的LINQ等效项.
Concat
is the LINQ equivalent of UNION ALL
in SQL.
我已经在LINQPad中建立了一个简单的示例,以演示如何使用Union
和Concat
.如果您没有 LINQPad ,请获取它.
I've set up a simple example in LINQPad to demonstrate how to use Union
and Concat
. If you don't have LINQPad, get it.
为了能够看到这些设置操作的不同结果,第一和第二组数据必须至少有一些重叠.在下面的示例中,两个集合都包含单词"not".
In order to be able to see different results for these set operations, the first and second sets of data must have at least some overlap. In the example below, both sets contain the word "not".
打开LINQPad并将语言"下拉列表设置为C#语句.将以下内容粘贴到查询窗格中并运行它:
Open up LINQPad and set the Language drop-down to C# Statement(s). Paste the following into the query pane and run it:
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中的结果如下:
The result in LinqPad looks like this:
这篇关于如何在LINQ中使用Union All?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!