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 good tutorial on UNIONS in linq.
select top 10 Barcode, sum(ItemDiscountUnion.AmountTaken) from (SELECT d.Barcode,SUM(AmountTaken) AmountTaken FROM [Aggregation].[dbo].[DiscountPromotion] d GROUP BY d.Barcode UNION ALL SELECT i.Barcode,SUM(AmountTaken) AmountTaken FROM [Aggregation].[dbo].ItemSaleTransaction i group by i.Barcode) ItemDiscountUnion group by Barcode
Note the original SQL is merging the 2 selects NOT concatenating them. I need to know how to merge the results i.e. removing duplicates and summing the rows amount value where there is duplication based on bar code.
LINQ Union operator is used for finding unique elements between two sequences (Collections). For example, suppose we have two collections A = { 1, 2, 3 }, and B = { 3, 4, 5 }. Union operator will find unique elements in both sequences. { 3 } element is available in both sequences.
LINQ Union is an extension method that requires two collections to combine the two collections and returns the distinct elements from both collections. LINQ Union supports only method syntax; it does not support the query syntax. The Union method presents in both the classes Queryable class and Enumerable class.
LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the . NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With