Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

Aggregate, LINQ, c#

The following code finds a list of Quantity values ok.

Question: At line 2, how aggregate could be applied to this code to get total quantity?

            Dim s List(Of Order)= (From o In db.Orders Where o.ID = 2).ToList()

            Dim sum = From o In s.OrderItems Select Total = o.Quantity

Open in new window

Avatar of it_saige
it_saige
Flag of United States of America image

Are you looking for something like this:
Imports System.Linq

Module Module1
	Private orders As New List(Of Order) From _
	 { _
	  New Order() With {.ID = 1, .Quantity = 5}, _
	  New Order() With {.ID = 2, .Quantity = 12}, _
	  New Order() With {.ID = 3, .Quantity = 7}, _
	  New Order() With {.ID = 2, .Quantity = 2}, _
	  New Order() With {.ID = 1, .Quantity = 1}, _
	  New Order() With {.ID = 3, .Quantity = 8} _
	 }

	Sub Main()
		Console.WriteLine(String.Format("Quantity of Orders for OrderID 2 = {0}", (Aggregate order As Order In orders Where order.ID.Equals(2) Into Sum(order.Quantity))))
		Console.ReadLine()
	End Sub
End Module

Class Order
	Property ID() As Integer
	Property Quantity() As Integer
End Class

Open in new window


Produces the following output:User generated image
-saige-
Avatar of Mike Eghtebas

ASKER

Hi Saige,

Orders is in Entity Framework define by db and has data in it.

Dim db As New TestDatabaseEntities


I want to pull that data. If I were doing it in SQL:

Select Sum(o.Quantity) From tblOrders  o Where o.ID =2

or

Select o,ID, Sum(o.Quantity) From tblOrders  Group By o.ID Having ID =2
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial