I have to perform the following SQL query: select answer_nbr, count(distinct user_nbr) from tpoll_answer where poll_nbr = 16 group by answer_nbr The LINQ to SQL query
I have the following SQL query to return all Customers who have no OrderLines with no Parts assigned - i.e. I only want the customers within which every order line of every order has no parts assigned - (in the actual problem I am dealing with a different domain but have translated to customers/orders to illustrate the problem)
SELECT c.Customer_PK FROM Customers c INNER JOIN Orders o[code].....
This works but generates less than optimal SQL - it is doing a subquery for Count on each row of the customers query rather than using Group By and Having. I tried making the LINQ Group By syntax work but it kept putting the filter as a WHERE not a HAVING clause.Edit in response to Answers below: I am accepting JamieSee's answer as it addresses the stated problem, even though it does not produce the GROUP BY HAVING query I originally had.I am a VB developer so I have had a crack translating your code to VB, this is the closest I got to but it does not quite produce the desired output:
Dim qry = From c In context.Customers Group Join o In context.Orders On c.Customer_PK Equals o.Customer_FK Into joinedOrders = Group[cod].....
The problem I had is that I have to push "jl" into the Group By "Key" so I can reference it from the Where clause, otherwise the compiler cannot see that variable or any of the other variables appearing before the Group By clause.With the filter as specified I get all customers where at least one order has lines with no parts rather than only customers with no parts in any order.
My head is fuzzled with this. I have an xml doc which has the layout for a grid stored in it. If you notice the columns are stored as "Items" in the XML. I am trying to retrieve each "Item" out of the XML using LINQ but no matter what I do I keep taking on straggler properties that I don't need.
In MS Reports, I have a tablix(table) where I group on foo. How do I get the count for each group? This is how I would do it for the total count: =Count(Fields!foo.Value) , but it's not enough.
Dim idQueuedJobs As IDictionary(Of Int32, KeyValuePair(Of String, Int32)) = New Dictionary(Of Int32, KeyValuePair(Of String, Int32))
Why duplicate KeyValue pair? This is because the first Int32 is just a normal index, and the String followed by another Int32 contains systemnames and the priority of the qued job in idQueuedJobs
I want to calculate the total number of systemnames in idQueuedJobs, how can i obtain this count by using the groupby method?
Something like this maybe?
numberOfSystems As Int32 = idQueuedJobs.Values.GroupBy(...)
I have the following LINQ statement, which performs a simple linq query and assigns the resulting values labels on an asp.net web form:
Dim db As New MeetingManagerDataContext Dim q = From s In db.vwRoomAvailabilities _ Where s.MeetingID = lblMeetingID.Text _
[code]....
Originally, there was going to be only a single row result and you can see I'm using FirstOrDefault() to grab that single value which works great. But the design has changed, and multiple rows can now be returned by the query. I need to now Group By the MeetingID above, and SUM each of the selected columns (i.e. s.AllRequestedDoubles).
I have a list of object with 3 properties (quantity, service, name)I want to have all names and services in my list (kinda cross join) and the grouped quantity of the row corresponding. Not clear i guess
Quantity Service Name 3 Srv2 Bob 4 Srv2 Paul 2 Srv1 Paul 1 Srv2 Nick
I want as output All the services and all the names and corresponding quantities (0 if none)
Srv1 Paul 2 Srv1 Bob 0 Srv1 Nick 0
[code]....
Here is what I got so far, but I dont even get the expected resultsAnd I am acutally certain there is a pretty easy way of achieving what i want...
Dim services = (From a In interventions Select New With {.Service = a.Service}).Distinct() Dim months = (From b In interventions Select New With {.Month = b.DateHeureIntervention.Month}).Distinct() 'Dim query = (From s In services _
I have a table "People" with the following columns:
-FullName (nvarchar not null) -DOB (datetime null)
I want to write a LINQ to SQL to group the people by age, like following result:
Age 19: 4 ppl Age 20: 5 ppl Age 21: 6 ppl Here's my try: Dim query = From ppl In db.People _ Select New With {.Age = DateTime.Now.Year - CDate(ppl.DOB).Year, .CountAge = ppl.Count}
Notice that there are no DOB record for some people in the tables, so these shall not be included. The DOB column has record like this 1982-10-24 10:12:45 AM because it's a DateTime column.
I have a Linq Group By query that works. Here's the query:
Dim query = From fb As Feedback In lst Where fb.Seller.login_name.ToLower = UserName.ToLower Order By fb.transaction_id Descending, fb.creation Descending _
[Code]...
I don't like working with anonymous types so I'm trying to delare the result and am hitting an InvalidCastException.
I have a Linq Group By query that works. Here's the query:
Dim query = From fb As Feedback In lst Where fb.Seller.login_name.ToLower = UserName.ToLower Order By fb.transaction_id Descending, fb.creation Descending _ Group fb By fb.transaction_id _ Into Group
I don't like working with anonymous types so I'm trying to delare the result and am hitting an InvalidCastException.
So, armed with this information, here's the declaration used:
Dim query As IEnumerable(Of IGrouping(Of Int32?, IEnumerable(Of Feedback)))
Here's the error returned:
Unable to cast object of type 'System.Linq.GroupedEnumerable`4[Feedback,System.Nullable`1[System.Int32],Feedback,VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]' to type
I'm trying to figure out how to use Group Joins in LINQ queries under VB.net. For some reason, every example I seem to find on the syntax is just plain At least, that's what my compiler keeps telling me. This is a simple example where I want to join orders to their order items so that I end up with a type that contains a collection of order items grouped together by their orderId's:
Dim groupedOrders = (From o In orders Group Join i In orderItems On o.OrderId Equals a.OrderId Into myOrders Select o.OrderId, myOrders).ToList()
What I'm currently running into in this example is that the 'myOrders' group I'm creating errors out with: Definition of method 'myOrders' is not accessible in this context.
I have the following linq statement to go through a dropdown menu's sub items and get what items are checked: vb Dim UnselectedItems = From xItem As ToolStripMenuItem In tsiSelectObjects.DropDownItems Where TypeOf xItem Is ToolStripMenuItem AndAlso CType(xItem, ToolStripMenuItem).Checked = False
I get this error tho: Unable to cast object of type 'System.Windows.Forms.ToolStripSeparator' to type 'System.Windows.Forms.ToolStripMenuItem'. As you can probably guess i have ToolStripMenuItems and separators in there
However the AndAlso should short circuit in the case where the item is not a ToolStripMenuItem and it doesn't seem to be doing so (as TypeOf xItem Is ToolStripMenuItem=false in this case)?
I have a user input screen that allows them to select input values and the resulting query is dependent on which values the user entered. The resulting query groups up the results to present a list of unique customers
Simplified table design - A customer can be in many states [code...]
I have the following query that groups parking spaces by their garage, but I can't figure out how to iterate the data in the view.
Public Function FindAllSpaces() Implements ISpaceRepository.FindAllSpaces Dim query = _ From s In db.spaces _ Order By s.name Ascending _
[code]....
The controller is taking the query object as is and putting it into the viewdata.model and as stated the view is not currently strongly typed as I haven't been able to figure out how to do this. I have run the query successfully in linqpad.
I have a list of attachments that I need to group by clientCLID and EmailAddress. From this grouped list I only need a list of clientCLIDs. After fiddling for a while I've managed to get it to work as follows:
I spent a lot of time on this problem. I am able to do simple Group By LINQ queries (on one property) but for multiple fields I'm a little stuck... Here is a LINQPad sample of what I want to do :
dim lFinal={new with {.Year=2010, .Month=6, .Value1=0, .Value2=0}, new with {.Year=2010, .Month=6, .Value1=2, .Value2=1}, new with {.Year=2010, .Month=7, .Value1=3, .Value2=4},
I have a table that has a 2 part key; an ID column, and a version number. I'm trying to select 'only the latest version' of the records.I'm trying to use the expression style of LINQ, to achieve a GROUP BY, and pull out the aggregate MAX value of the Version. However no aggregation is taking place.
syntax of the LINQ query to use GROUP something BY something and select some fields of the datatable. i am having a datatable filled with some rows, i am trying to fill the datagridview with the GROUP BY query output of some fields.
Dim queryX = From m In db.Master Where m.Field = value Group Join d In db.Detail On m.Id Equals d.MasterId Into Group Where d.Field = value
In English, I want to join the master and detail tables, specifying conditions on each. But this causes the following compiler error:
"Name 'd' is either not declared or not in the current scope."
It works if I put this same condition in functional form:
Group Join d In db.Detail.Where(Function(x) x.Field = value)
but I think this is more typing, harder to understand, and introduces that irritating dummy variable. I really would prefer to use the query comprehension syntax. Is there a way to accomplish this?
The following data is created by joining two sql tables together:I would like to group together distinct rows of DateStamp/UserName/ StudentName/ InstructorName/TableName/PrimaryKey (I'll call this 'group records') and then group under these ColumnName/PreviousValue/NewValue (I'll call this 'subgroup records')The end result would be that I could iterate through the 'group records' - there would be 5. In each 'group record', I could then iterate through the 'subgroup records'. The 5 groups would contain 3, 2, 5, 2 and 1 subgroup records respectively.What would be the syntax to create a query to do this? Ideally this would be in a vb.net linq syntax.
myFilteredContractors = (From c In myFilteredContractors Join cc In myConClasses On c.ContractorId Equals cc.ContractorId Where inClassifications.Contains(cc.ClassificationId)[code].....
This is properly ordering this list of contractors by the number of classifications that they have.I also want to order them by whether or not they have a field set (CompanyOverview), which if is an empty string should be below those contractors who have set their CompanyOverview. Also, after the CompanyOverview is ordered I want to order by Registration Date.So it should order by:
Number of Classifications Whether Overview has been set (c.CompanyOverview) Registration Date (c.AppliedDate)