I have the following Transact SQL query using a union. I need some pointers as to how this would look in LINQ i.e some examples wouldbe nice or if anyone can recommend a goo
Three useful Linq concepts operating on sets. Given set c
and set e
:
Concat gives you everything in c
or e
:
(From c In db.Customers Select c.Phone).Concat( _
From c In db.Customers Select c.Fax).Concat( _
From e In db.Employees Select e.HomePhone)
(From c In db.Customers _
Select Name = c.CompanyName, Phone = c.Phone).Concat(From e In db.Employees _
Select Name = e.FirstName & " " & e.LastName, Phone = e.HomePhone)
Union also gives you everything in c
and e
, but removes any duplicates:
(From c In db.Customers _
Select c.Country).Union(From e In db.Employees _
Select e.Country)
Except gives you everything in c
that is not in e
:
(From c In db.Customers _
Select c.Country).Except(From e In db.Employees Select e.Country)
There are the 101 Linq Samples - with two union samples Union1 and Union2
This Linq statement should get you the same results as your SQL: (it has for me on a test record-set)
var results = (from a in (from d in DiscountPromotions
group d by d.BarCode into g
select new {
BarCode = g.Key,
AmountTaken = g.Sum(p => p.AmountTaken)
}).Union(from i in ItemSaleTransactions
group i by i.BarCode into o
select new {
BarCode = o.Key,
AmountTaken = o.Sum(i => i.AmountTaken)
}) group a by a.BarCode into b
select new {
BarCode = b.Key,
AmountTaken = b.Sum(c => c.AmountTaken)
});
Here's an example of a generic union, without regard to the scenario you posted:
var something =
(from e in _repository
select new { e.Property1, e.Property2 }).Union(
(from e in _repository
select new { e.Property1, e.Property2 }));