Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to do in LINQ??

Posted on 2016-09-16
18
Medium Priority
?
81 Views
Last Modified: 2016-09-21
I am using vb.net. I have a data table with these columns:
Dep
Qty
Cost
Sales

In SQL I would do:
Select
Max(Dep) dep,
count(*) cnt,
Sum(qty) qty,
Sum(Cost*qty) Cost
Sum(sales*qty) Sales
From tbl
Group By dep
Order By dep

How can I do this in LINQ?
0
Comment
Question by:Jess31
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
  • 3
  • +1
18 Comments
 
LVL 15

Expert Comment

by:Ess Kay
ID: 41801564
You can have a look at these tools to convert SQl to LINQ:

LINQPAD - https://www.linqpad.net/  (Free)

or Linqer http://www.sqltolinq.com/ (paid)
0
 
LVL 1

Author Comment

by:Jess31
ID: 41801628
I tried LINQPAD, it runs my query, but I don't see how to get the conversion to LINQ
0
 
LVL 15

Expert Comment

by:Ess Kay
ID: 41801818
Theres an example here


https://sampathloku.blogspot.com/2012/08/how-to-convert-linq-entity-query-into-t.html

It does linq to sql, just check the other options to convert it backwords
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41801948
Hi Jess31;

See if this give you what you are looking for.
'' Change all Field(0f Integer) to the correct DataType
Dim results = (From r In dt.AsEnumerable()
               Group r By Key = r.Field(Of Integer)("Dep") Into depGroup = Group
               Order By Key
               Select New With {
                   .Dep = Key,
                   .Cnt = depGroup.Count(),
                   .Qty = depGroup.Sum(Function(q) q.Field(Of Integer)("Qty")),
                   .Cost = depGroup.Sum(Function(c) c.Field(Of Integer)("Qty") * c.Field(Of Integer)("Cost")),
                   .Sales = depGroup.Sum(Function(c) c.Field(Of Integer)("Qty") * c.Field(Of Integer)("Sales"))
               }).ToList()
               

Open in new window

0
 
LVL 1

Author Comment

by:Jess31
ID: 41802011
yes, I see his seems to return the SQL for the LINQ but for me it doesn't return the LINQ from the SQL

linq1.png
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41802019
To your statement, "yes, I see his seems to return the SQL for the LINQ but for me it doesn't return the LINQ from the SQL". Are you querying the SQL database or the DataTable object in code?
0
 
LVL 1

Author Comment

by:Jess31
ID: 41802061
SQL Database. The Datatable is created in code, I don't know if I am able to query against it in this tool
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41802075
Are you using the SQL database to get the information you posted in the question or have you crated a DataTable object and filled it in some other means and wish to query that DataTable?
0
 
LVL 1

Author Comment

by:Jess31
ID: 41802098
I am using a table on SQL DB that is similar to the DataTable against which I want to run LINQ
0
 
LVL 15

Expert Comment

by:Ess Kay
ID: 41802101
Jess, My mistake,


Linqpad doesn't convert SQL to LINQ, only the other way (LINQ to SQL)  It relies on the .Net Linq-to-Sql library or Entity framework for the translation.
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41802104
So if you are wanting to query the DataTable object that is in local memory then try my last post that has the Linq query. Also in that query you will need to change, dt in dt.AsEnumerable(), to your actual instance name for the DataTable object.
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41802171
*NO POINTS*

Proof of concept:
Imports System.Data.SqlClient

Module Module1
	Sub Main()
		Dim adapter As SqlDataAdapter = Nothing
		Dim table As DataTable = Nothing
		Dim [list] As List(Of Department)
		Try
			Connection.Open()
			If Connection.State.Equals(ConnectionState.Open) Then
				table = New DataTable()
				[list] = New List(Of Department)()
				adapter = New SqlDataAdapter("SELECT * FROM SALESTABLE", Connection)
				adapter.Fill(table)
				For Each row As DataRow In table.Rows
					[list].Add(New Department() With {.Department = row("DEPT"), .Quantity = row("QTY"), .Cost = row("COST"), .Sales = row("SALES")})
				Next
			End If
		Finally
			If adapter IsNot Nothing Then adapter.Dispose()
		End Try
		Dim a1 = (From row In table
				Order By row("DEPT")
				Group row By DEPT = row("DEPT") Into g = Group
				Select New With
					  {
						Key DEPT,
						    .CNT = g.Count(),
						    .QTY = g.Sum(Function(x) x("QTY")),
						    .COST = g.Sum(Function(x) x("COST") * x("QTY")),
						    .SALES = g.Sum(Function(x) x("SALES") * x("QTY"))
						 })
		Dim a2 = (From item In [list]
			Order By item.Department
			Group item By DEPT = item.Department Into g = Group
			Select New With
			{
				Key DEPT,
				    .CNT = g.Count(),
				    .QTY = g.Sum(Function(x) x.Quantity),
				    .COST = g.Sum(Function(x) x.Cost * x.Quantity),
				    .SALES = g.Sum(Function(x) x.Sales * x.Quantity)
				})

		Console.WriteLine("From a datatable")
		For Each group In a1
			Console.WriteLine(group)
		Next

		Console.WriteLine()
		Console.WriteLine("From a list")
		For Each group In a2
			Console.WriteLine(group)
		Next
		Console.ReadLine()
	End Sub
End Module

Module Globals
	Public Property Connection() As SqlConnection = New SqlConnection("Data Source=.;Initial Catalog=EE_Q28970321;Integrated Security=True")
End Module

Class Department
	Public Property Department() As Integer
	Public Property Quantity() As Integer
	Public Property Cost() As Decimal
	Public Property Sales() As Decimal
End Class

Open in new window

From a set of data in the database -Capture.JPGProduces the following output from SQL -Capture.JPGAnd the following output from the application using LINQ -Capture.JPG-saige-
0
 
LVL 1

Author Comment

by:Jess31
ID: 41807518
Fernando Soto
I got the code to do the Group Totals, etc.
If I just wanted total aggregation with not groups what change do I need to make ?
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41807586
Please post the query you are working with. When you say, "If I just wanted total aggregation with not groups", does that mean you do not want any Grouping?
0
 
LVL 1

Author Comment

by:Jess31
ID: 41807654
Right not grouping.
dt =
Name
Salary
Benefits

And I want grand total of Salary and Benefits (name is ignored)
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 41807743
Hi Jess31;

Something like this should work.
Dim results = (From r In dt.AsEnumerable()
               Group By Key = "OneGroup" Into justOneGroup = Group
               Select New With {
                   .Salary = justOneGroup.Sum(Function(s) s.Field(Of Integer)("Salary")),
                   .Benefits = justOneGroup.Sum(Function(c) c.Field(Of Integer)("Benefits")
               }).ToList()

Open in new window

But the fields are not the same, is this a different question?
0
 
LVL 1

Author Comment

by:Jess31
ID: 41808724
But I am asking specifically w/o Grouping, just grand totals
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 41808832
Hi Jess31;

I know you did. I needed to group so that I can do the Sum function so I grouped ALL rows into one group which then allowed me to do the calculations, not really grouping.
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question