LINQ Query To Group Data Between Two List Collections, Populating A Nested Object
Oct 26, 2011
I have these objects:[code]Using LINQ I need to take a List(Of MakeInfo) and a List(Of ModelInfo) and aggregate the StockInfo from ModelInfo into the List(Of MakeInfo).So for each MakeInfo I will have a total count of all stock where MakeInfo.Name = ModelInfo.Make, and also a minimum price.I think it's going to be something like this, but I'm having trouble accessing the nested object and not sure if it's going to be possible with a single query.[code]
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.
I have a generic list - SupportedTypeGroups. Each SupportedTypeGroup has SupportedTypes property (generic list of SupportedType). How to construct a Linq query to locate SupportedType with required name?
I'm writting a graph algorithm and I'm almost there...My algorithm stores several edge objects in a collection of edges, representing a path from initial vertex to final vertex.hus, there should be also several paths between those vertexes (several collections of edge type), stored in another collection (in my class, callded "collswap").Each edge is an object which have two vertexes: initial (v) and final (w), in this way:
dim manhattan as new vertex dim brooklyn as new vertex dim statenIsland as new vertex
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.
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.
How do I order by and group by in a Linq query?I tried..Dim iPerson = From lqPersons In objPersons Where Len(lqPersons.Person) > 0 Group lqPersons By key = lqPersons.Name Into Group Order By Group descending Select Group, key
For Each i In iPerson tmp = tmp & vbNewLine & i.key & ", " & i.Group.Count Next
I am trying to do a simple summary of table data using a LINQ query.a regular SQL Query looks like:[code]This query works fine and returns the correct results.[code]This LINQ query returns the incorrect results some of the time. Off by .01 in most cases.The "value" column is of type Numeric (12,2) in the database.Now when I show the values from the Sum in a msgbox I get extra precision and thus incorrect results as my end result because of rounding.For example I get 835.18 + 54.62 = 889.80960 from the above LINQ query.I am running Visual Studio 2008 9.0.30729.1 SP on Vista 64Bit with .NET 3.5 SP1.
My LINQ query contains the following Group By statement:
Group p By Key = New With { _ .Latitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Latitude, _ .Longitude = p.Address.GeoLocations.FirstOrDefault(Function(g) New String() {"ADDRESS", "POINT"}.Contains(g.Granularity)).Longitude}
The query works, but here is the SQL that the clause above produces
SELECT [t6].[Latitude] FROM ( SELECT TOP (1) [t5].[Latitude]
[Code]....
but this produced an error: "A group by expression can only contain non-constant scalars that are comparable by the server."
I am working on making a Windows based application within Visual Basic 2008 Express that could potentially be used for a music school as a project. This application is connected and bound to a Microsoft Access database. Within this application I have a form for adding a new appointment reservation. This form has a combo box that the user can select the lesson type (eg. "I want a piano lesson"). Upon being changed, a list box would be populated with the names of all instructors that have that selection as either their primary or secondary talent.So, my database is bound, the query is written (correctly...i hope), and I don't know how to 1) select the table column that I want displayed in the list box and 2) actually display the query results within the list box. Is this making sense? Probably not, bu
Private Sub cmbLessonType_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLessonType.TextChanged 'populate the lboInstructor box
I'm quite new to Visual Basic - using Visual Studio 2008 and can't seem to find a way to do the following:
I have a few tables in a SQL Server database and have used LINQ to SQL to create classes of those tables.
Here's a cut down example of what I'd like:listbox1 filled with table names - APS, SMPS, WCPC, CFLAPS Then from the SelectedIndexChanged event, listbox2 should populate column headers of the selected table.
I have no issues getting data from the database, and can access all of these headers through the anonymous type objects created from a LINQ query (eg APS.ID, APS.count etc), but populating a listbox with these variable names rather than the data inside them seems rather elusive.
This is probably a cross platform coding question rather than VB specific, so if you have a solution in C# or whatever I'd be happy if you could let me know.
Dim query = From o In myContainer.MyObjects Select o.MyStringProperty Distinct Dim myProperties As List(Of String) = query.ToList????? 'no way!!!' "query" type is IEnumerable(Of String)
I tried to use the query directly as a DataSource of a (infragistic) combobox, but it throws me NullReferenceException, so I decided to convert it to a listof strings, to be a more "classical" datasource.
Dim values As List(Of String) = query.AsQueryable().ToList() does not work either: Value of type 'System.Collections.Generic.List(Of System.Linq.IQueryable(Of String))' cannot be converted to 'System.Collections.Generic.List(Of String)'.
I have created a Dictionary class (MyDictionary for the example). I am currently trying to pass MyDictionary into a function, filter it into a new instance of MyDictionary and pass this new instance into another method. When I am attempting to create the second instance from the filtered first instance of MyDictionary via Lambda Expressions and the ToDictionary Method, I am getting the following error:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'MyDictionary'. I have simplified the example and recreated it in LINQPad and am getting the same error.
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9.
Let's say I have an employee class with ID, Forename, Surname, Initials and Email Address properties.
At present, you can construct an Employee object by passing a data row which, typically will include all these fields. However, sometimes I only want the ID, Forename and Surname but still want to populate an object.
[Code]...
However obviously if certain fields are not present in the data row, I will have an error. Is there a quick way of populating the object based on the fields that are present within the data row without a) having to have separate subs for each circumstance and b) without having to try / catch (or something similar) around each property? I know other languages have options like this - where if there is no value, it will be another value (i.e. a default).
I am using VB .Net for this, so I don't have access to var or this would be a simple matter.Right now my query is as follows
[code]...
So I used this query in LinqPad to help me determine what the object would look like. I got back a IOrderQueryable(Of RSError) which then contained a IGrouping(Of String, RSError) for each grouped collection of objects returned by the query.However I ended up with the current object type of errors as IOrderedQueryable(Of IGrouping(Of String, RSError)) because of the cast error I am getting in VS.
[code]...
I'm not sure how to get rid of the VB$AnonymousType_1 Part of the returned object.Am I even on the right track here or am I missing something completely?
I have a the following Class structure. Company > List(of Departments) > List(of Employees) I want to Query a Company to find out if it has a department of the following name and a Employee in that department with the following ID! How could I query this. The way I have the code it expect to return one department so I have it doing
Is there any particular reason why creating a reference to an object in an IEnumerable Linq query would be really slow? I have a Linq query list consisting of my own objects (count is about 200).I was doing a time-critical task, and this line (which was used a lot in a loop) took nearly a millisecond to execute:
Dim l as IList(Of Foo) = (From dataRow As DataRow In table.Select() Where CStr(dataRow("Column1")) = "A" Select New Foo(CStr(dataRow("Column1")), _ CStr(dataRow("Column2")))).ToList()
What's happening is that if i set a break-point to the constructor of Foo and step, the constructor is hit and the parameters are loaded with the arguments. However, l has empty Foo objects (the members in every object are Nothing). What could be happening here?
I am using a path comparison to find any children tags which works well when there is only 1 tag selected. This is my code for when multiples tags are selected but it is not working. Can you point me in the right direction?
Single Tag Selection (working) Dim tagpath = uxTags.SelectedItem.Text lnqCases = From i In lnqCases Where i.HelpDeskTagItems.Any(Function(x)