2012-04-28 28 views
42

Cách sử dụng công đoàn tất cả trong LINQ TO SQL. Tôi đã sử dụng mã sau đây cho công đoàn, sau đó làm thế nào để sử dụng điều này cho công đoàn tất cả?Làm thế nào để sử dụng công đoàn tất cả trong 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

bạn nên đánh dấu câu trả lời Jon Crowell như 'chấp nhận' – arviman

Trả lời

87

Concat là LINQ tương đương UNION ALL trong SQL.

Tôi đã thiết lập một ví dụ đơn giản trong LINQPad để minh họa cách sử dụng UnionConcat. Nếu bạn không có LINQPad, hãy tải xuống.

Để có thể xem các kết quả khác nhau cho các hoạt động đã đặt này, bộ dữ liệu đầu tiên và thứ hai phải có ít nhất một số trùng lặp. Trong ví dụ bên dưới, cả hai tập hợp chứa từ "không".

Mở LINQPad và đặt trình đơn Ngôn ngữ thả xuống C#. Dán đoạn mã sau vào cửa sổ truy vấn và chạy nó:

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

Kết quả trong LinqPad trông như thế này:

enter image description here

Các vấn đề liên quan