Converting A Traditional SQL Aggregate Query Into A LINQ One - SUM Grouping ?

May 24, 2010

I'm having trouble getting my head around converting a traditional SQL aggregate query into a LINQ one. The basic data dump works like so:

Dim result =
(From i As Models.InvoiceDetail In Data.InvoiceDetails.GetAll
Join ih As Models.InvoiceHeader In Data.InvoiceHeaders.GetAll On i.InvoiceHeaderID Equals ih.ID

[CODE].....................

What I need to really be getting out is ih.Period (a value from 1 to 12) and a corresponding aggregate value for i.ExtendedValue. When I try to Group ih I get errors about i being out of scope/context.

View 1 Replies


ADVERTISEMENT

C# :: Aggregate Or Join Strings In Linq To Sql Query (SQL Server)?

Aug 6, 2010

Given a table like

ID | Name | City
1 | X | Y
2 | Z | Y

[code].....

View 2 Replies

.net - Converting Linq To XML Query From C# To .Net?

Dec 1, 2009

I'm converting the Linq query below from C# to VB.Net. Can you spot my error? The query joins 3 XML datasets. C# - This one works great.

List<Course> courses =
(from course in CourseXML.Descendants(ns + "row")
join coursecategory in CourseCategoryXML.Descendants("Table") on (string)course.Attribute("code") equals (string)coursecategory.Element("DATA")

[code]....

View 2 Replies

How To Use Aggregate Function In LINQ

Nov 1, 2011

I want to get the average of this query.
From d In (From c In location.Descendants("temperature")
Where c.Attribute("type").Value = "hourly" Select c).Descendants("value")
Take 3
Select d
I can see the aggregate keyword in the autocomplete dropdown, but how to apply it.

View 2 Replies

LINQ - Logical Difference Between Max And Aggregate?

Apr 6, 2011

I've seen the operator Max used two different ways. The following two queries produce the same results. The MSIL code is slightly different. What is the benefit of using the Aggregate operator? Logically, is there a difference?

[Code]...

View 3 Replies

LINQ Expression Starting With From And Aggregate

May 4, 2012

[code]The LINQ query going into "result" is incomplete because I'm stumped at what is happening there. I expect FirstOrDefault to refer to refer to a single Child object at that point in the expression, but it refers to a collection of child objects. Why? What is the best way to get a list of parents that have no associated child or have a child fitting a particular condition? (My actual code will have one child max, so this sample code is not representative.)I just don't understand what the collection of FirstOrDefault could be referring to. It should really be just 1 value or nothing at all times.

View 1 Replies

IDE :: Aggregate Query With Condition ?

May 28, 2012

i have 1 query with aggregate with condition using access

SELECT
HD.No,
SUM(IIf(DT.Status = 'A', 1, 0)) AS One,[code]...

i can run it in access but not in .Net QueryBuilder

View 2 Replies

Run Aggregate Query Against A Datatable?

Mar 9, 2010

I do have a datatable filled from a flatfile (say .txt). After the datatable is populated, I manipulate the data. After datamanipulation I want to do some analysis of the content of the datatable. For this analysis, I need to aggregate the data.

To keep it simple, let's say I have single orders of customers in the datatable and now I want to get the total order amount for each customer (SQL: SELECT Customer, Count(Ordervalue) FROM Ordertable GROUP BY Customer).

View 5 Replies

Linq To Sql, Aggregate Columns ,group By Date Into Listview?

Aug 3, 2011

also i have a table called Orders with several columns, they contain information about the order and store the ID of the Customer they belong to.Question is: how can i query that table with (preferably) linq (the datacontext is from LinqToSql) to return the following dataI want to search for any entry with the matching CustomerID which took place, group them by Year, Sum the Totals respectively and add them to the listview?I now i could use lamda expressions and aggregate, its just not clear how (option infer on,db is a datacontext object,CustomerID is an int32 variable):

Dim Orders = (From order In db.Orders Where order.CustomerID = CustomerID).GroupBy(Function(p) p.Date.Year).GetEnumerator
I reckon i'd have to create an anonymous type like the following:

[code].....

View 1 Replies

Linq-to-Entities Aggregate A Column That Is Calculated In An External Function?

Feb 21, 2011

I want to Sum of the calculated column Red which is calculated in the Function IsRed() that return an integer.When I run the query I get the following error: Method 'Int32 IsRed(Int32)' has no supported translation to SQL.How should I rewrite this to get it to work.

[Code]...

View 2 Replies

MS CRM 2011 + FetchXML - Aggregate Query Limit Exceeded?

Apr 12, 2012

I've got a 2 part question: First question: I know that there is a query limit of 5,000 records when querying records, for performance reasons, but is there a limit when doing an aggregate query? If so, what is it? I need only to query the number of records and for one entity I can get a result of 39,000+ records, but for another entity I see an error message like:

[Code]...

View 1 Replies

.net - Grouping Using LINQ?

Feb 5, 2010

I'm having a heck of a time with transforming a simple SQL Query into a LINQ query(using vb btw)

Here is my SQL:
SELECT USRDEFND5
FROM int_gp_employee
GROUP BY USRDEFND5

[Code]...

I've tried a number of different variations of the LINQ. My current statement is:

From b In xmlFile...<row> Group b...<usrdefnd5> By b...<usrdefnd5> INTO group when I foreach through the resulting collection, EVERY line (17000) shows up.

View 2 Replies

.net - Linq Nested Grouping?

Jul 7, 2009

I've a large table of Items and I need to organize them by Category, then by Year and then by Month.Item has CategoryID and Dated properties.I got this far:

Dim Items = From Item In DB.Items _
Group By CategoryID = Item.CategoryID _
Into Categories = Group _
Order By CategoryID

But where I put the:

Group By Year = Year(Item.Dated)

and the

Group By Month = Month(Item.Dated)

The final result should be something like this:

For Each Category in Categories
For Each Year in Category.Years

[code].....

View 2 Replies

Datatable Grouping Using Linq?

May 25, 2011

I'm completely dense here, but I'm trying to get some stats from a DataTable. One of the columns in the datatable is called "colour".I need to find out how many of each instance of "colour" are in the datatable.

I'm trying:
Dim q = From p In PGWorkingDataTable _
Group p By p("colour") Into Group _

[code].....

View 2 Replies

Counting Orders And Grouping Them, Linq To Sql?

Aug 15, 2011

I have a table called Ordersthe table has many rows but im only interested in two in particular.I want to query the table so it returns the average ordered count of each producti want to know what is the average count of the ordered products, but now in total but per productID instead.

View 1 Replies

Grouping A Generic List Via LINQ?

Jun 26, 2011

I need to take a collection and group it via Linq but all the examples I've seen fail in some manner or other with some syntax difference that I can't quite lick.

My collection:

Dim a As New List(Of ProcessAlert)
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Alert", 2))
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Document", 2))

[Code].....

View 1 Replies

Linq Grouping By Nullable Datetime And Using This As Criteria?

Nov 17, 2009

I am struggling with a nullable datetime column [DateInsp] in an ASP.NET app which uses SubSonic3, Linq, MS SQL Server 2005.I had this all working when the datetime column [DateInsp] did not allow nulls. A new requirement forced me to set the [DateInsp] column to allow nulls and now I am struggling getting this piece of functionality to work properly again.

Problem 1:I need to first render a dropdown list of the 7 most recent inspection dates for a given inspector (this is a grouped list of the 7 most recent dates for the inspector). Here is the TSQL that I need to convert to Linq syntax:

declare @InspectorID varchar(5)
set @InspectorID = 'GPA'
select top 7 convert(nvarchar(30), [DateInsp], 101) InspectedDate

[code]....

If I can't get this work properly using Linq, BUT I can/could build a stored proc to return the list of dates and throw that into a dropdown. Fair enough. I've been fighting with the Linq syntax?

Problem 2: I need to use the selected date in the dropdown mentioned above to pull the correct records for this inspector and the correct date. Again, this is a nullable datetime field and this is real sticking point for me.

Here was the original Linq syntax that accomplished the requirement before I had to change the datetime field to allow Nulls:

Dim query = (From i In db.IncomingInspections _
Where i.InspectorID = User.Identity.Name _
Group By Key = New With {i.DateInsp} Into Group _

[code]....

For some reason I can't use the .Value property; I get: The member 'Value' is not supported I get: "Incorrect syntax near '<'." if I try to add the date comparison to the where clause too.

View 2 Replies

LINQ To SQL Grouping Multiple Columns With A Distinct Row

Aug 9, 2010

I have the following table structure. I want to select distinct CustomerId and CustomerName, TotalCost.[code]

View 2 Replies

Return Max Record Count By Grouping In Linq?

Nov 9, 2011

I'm very new to linq and I'm trying to come up with a linq query against a dataset that will return a max count value based on grouping records.[code]...

View 1 Replies

Error : "You Have Tried To Execute A Query That Does Not Include The Spec Ified Expression 'ID' As A Part Of The Aggregate Function

Jul 1, 2009

I am working on an application in Visual Basic Express using an Access 2000 database.I am trying to get athe following SQL query to work but get an error in Access.

The query is:

SELECT [ID], [Title], [Author], [Series], [YearPublished], [ISBN], [CoverPrice], [Style], [Condition], [Signed], [Comments], Count([Title]) AS CountOfBooks, Sum([CoverPrice]) AS TotalCoverPrice
FROM tblBooks
WHERE ID=[@ID];

The error is:"You have tried to execute a query that does not include the spec ified expression 'ID' as a part of the aggragate function."

The query works fine without the 'Count' and 'CoverPrice' count and sum to the query.

View 1 Replies

Linq Grouping With Anonymous Types And Option Strict

Apr 24, 2012

I've got the below, where I'm grouping a collection by a propery, then wanting to access the properties of my group. Problem I have is with the anonymous typing. Because of option strict I have to give an explicit type but I can't work out what the type should be. The below doesn't compile because t.HeadAccountKey isn't a value (as t has a type of object). So either I need do some casting or my linq selector is wrong,

[Code]....

View 1 Replies

C# - Get A Result In A Grouping Query Which Is Value Agnostic And Has Dynamic Columns?

May 17, 2011

I have a table called Foo and I have two columns: Lorem and Ipsum, so the scheme of the table is:

Foo(Lorem, IpsumID)

I also have a table called IpsumTypes, which looks like this:

IpsumTypes(IpsumID, IpsumName)

I would like to write a LINQ query which will have the following result:

Headers: Lorem, IpsumName1, IpsumName2, ..., IpsumNamen
Values: Loremi, count(IpsumName1), ..., count(IpsumNamen)

Each row represents a group of Lorem value and the number of each possible IpsumID in the group. New rows can be added to the IpsumTypes table, rows can be deleted too, so I need dynamically generated columns, because at the time of writing the code I'm not aware of the possible values of Ipsum. How can I achieve this? Is there a magical Linq query which solves this problem, or should I get the values from the database and parse them separately, if speed counts?

View 2 Replies

LINQ Query Is Enumerated - Turn On Some Kind Of Flag That Alerts Me Each Time A LINQ Query Is Enumerated?

Sep 22, 2009

I know that LINQ queries are deferred and only executed when the query is enumerated, but I'm having trouble figuring out exactly when that happens.Certainly in a For Each loop, the query would be enumerated.What's the rule of thumb to follow? I don't want to accidentally enumerate over my query twice if it's a huge result.

For example, does System.Linq.Enumerable.First enumerate over the whole query? I ask for performance reasons. I want to pass a LINQ result set to an ASP.NET MVC view, and I also want to pass the First element separately. Enumerating over the results twice would be painful.It would be great to turn on some kind of flag that alerts me each time a LINQ query is enumerated. That way I could catch scenarios when I accidentally enumerate twice.

View 3 Replies

Use The Insert Key (like In Traditional Windows) For A WPF 4 App?

Sep 7, 2010

Ok, I know that the new versions of windows do not use the insert key by default and you have to program for it. I want to be able to type in my text box and override the content that is in it just like in old windows when you could activate the insert key. This is just for my WPF 4, VB.net Application.That what I meant: I need to mimic old terminals. I need to activate the overwrite mode programmatically for all the controls. The same affect as the 'Insert' key on the keyboard. Only that key does not work in a WPF environment.

View 2 Replies

.net - ActiveRecord Linq/NHibernate Linq Not Building Query Completely?

Jul 14, 2011

given this function:

Public Function Search(ByVal StartIndex As Integer, _
ByVal MaxResults As Integer, _
ByVal AccountNumber As String, _
ByVal LastName As String, _

[Code]....

instead of what I expected:

Select count(*) from remitline where lastname = "smith"

What am I doing wrong building up the where clause? I'm using Castle ActiveRecord 2.1

View 1 Replies

Performance Gain In LINQ Query Vs LINQ Stored Procedure?

Aug 6, 2009

if there is that much of a performance gain in running a LINQ stored procedure versus a LINQ query?

View 1 Replies

Asp.net - Complex Linq Query - Add A .Where() Or .Any() Predicate To Reduce Query Complexity (in VB)?

Sep 14, 2010

I have to join two main tables, and I need to filter the results by elements in an ASP.NET web form. These filters are created on the fly so I have to use a lot of where extensions to filter the query. I want to execute the query with as optimized SQL as possible.

I am first doing a simple join between TW_Sites and TW_Investigators. Then there are two sub-tables that are involved. TW_InvestigatorToArea and TW_InvestigatorToDisease. While most of the where clauses are working fine, I have found a performance issue that won't be an issue right now, but will be an issue as the table gets bigger.

The arrays DiseaseCategories and DiseaseAreas would be the results of a CheckBoxList result.

Protected Sub LoadResults()
'Get Dictionary of Filters
Dim FilterDictionary As OrderedDictionary = Session.Item("InvestigatorFilterDictionary")
' Initialize LinqToSql

[code]....

View 2 Replies

Convert Anonymous Type To Strong Type For Grouping Query?

Aug 30, 2010

I've pieced together some information from other posts but I'm stuck. The first part works fine. Basically I query the database using LINQ and then I loop through the results generating a report.

[Code]...

View 2 Replies

LINQ Query Using The Dynamic LINQ Library?

Mar 31, 2011

Forgive my ignorance on this.I have this LINQ Query:Dim ngBikersDataContext As New CarBikeWalkDataContext

bikersList = (From c In ngBikersDataContext.Reg_Bikers _
Order By c.L_Name _
Select New Bikers() With { _
.BikerID = c.BikerID, _
.F_Name = c.F_Name, _

[Code]...

with the error "Overload resolution failed because no accesible 'Select' accepts this number of arguments."
Over the "NEW" I get an error " ')'expected."

View 1 Replies

"System.ArgumentException: An Item With The Same Key Has Already Been Added." When Trying To Order An In-memory LINQ Query By A LINQ Association?

Jan 27, 2011

We are doing a query against an in-memory collection of LINQ data objects. The wrinkle is that we are ordering by a column in a related table whose records have not necessarily been loaded yet (deferred loading:)

Dim oPkgProducts = _
From b In oBillPkg.BillProducts _
Where b.Successful.GetValueOrDefault(Common.X_INDETERMINATE) = _

[code]....

View 1 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved