Order By And Group By In A Linq To Objects Query?

Sep 28, 2010

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

[code].....

View 5 Replies


ADVERTISEMENT

Linq Group By And Order By Multiple Conditions?

Jan 16, 2012

I have the following:

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)

Is it possible to all of this in LINQ?

View 1 Replies

Using Linq To Group, Order And Concatenate Strings

Jun 14, 2011

Suppose I have the following data

Key ID Data
A 1 Hello
A 2 World
B 2 Bar
B 1 Foo

I am looking to produce the result

A HelloWorld
B FooBar

I am struggling to get the syntax quite right - I was trying to use Aggregate, but I wasn't sure if I could (or should) use SelectMany

Dim data = result.Rows.
GroupBy(Function(r) r.Key).
Select(Function(g) g.OrderBy(Function(s) s.ID)).

[Code]....

View 4 Replies

Linq - Merge And Order 2 Lists Of Different Objects?

Mar 15, 2012

I have collections of 2 different types - let's call them Cars and Trucks. Both share base class Vehicle, which has property Passengers.I want to merge them into a single collection ordered by that property. E.g., merge Cars and Trucks and order by Passengers.

View 2 Replies

LINQ Objects - Group All The MyObjects Together That Share The Same Value And Then Return That Value?

Nov 16, 2010

I am having trouble following some of the examples at MSDN for LINQ.Basically I have a List Of MyObject. MyObject has a property called Value which is an integer.I want to group all the MyObjects together that share the same Value and then return that Value where the count of the group is greater than 5.I have tried the following,

dim foak = From o as MyObject in MyObjectList _
Group o By o.Value into Count _
WHERE Count > 5 _
Select o.Value

View 2 Replies

Get A Linq To Sql Group By Query Into The Asp.net Mvc View?

Dec 23, 2009

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.

View 2 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

How To Group Distinct Columns In A Linq Query

Nov 4, 2010

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.

View 1 Replies

C# Linq Query Conversion For Order An ObservableCollection?

Apr 12, 2012

I've a structure collection like this:

Jet Owner Item Comp
AAAA AAAA 101 2210
AAAA AAAA 202 2220

[code].....

View 1 Replies

Datagridview Column Order From Linq Query?

Mar 19, 2010

I am using a modal form with a datagridview in order to populate textboxes on a parent form. The datagridview is bound to an anonymous type resulting from a linq query, which varies depending on the textbox control whose keypress event is called. I always want to display a key value in column 0 of the datagridview (along with a variable number of additional columns), and then use that key value once the user selects a row.

However, when setting an anonymous type from a linq query as the datasource for a datagridview control, the columns are indexed alphabetically rather than in the sequence selected in the query. This requires setting the displayindex as a workaround, and then keeping track of which column contains my key value. I read elsewhere that this was something fixed in VS2008 SP1, but I still encounter the behavior.

View 1 Replies

LINQ Query With Sum And Group By Is Adding Decimal Precision

Aug 24, 2009

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.

View 3 Replies

Optimize Linq To SQL Query, Group By Multiple Fields

Jul 26, 2010

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."

View 1 Replies

Sql - Group By Having And Count As LINQ Query With Multiply Nested Tables?

Feb 28, 2012

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.

View 3 Replies

Asp.net - Linq Group By An Entity And Then Order By The Grouped (nullable) Entity

Jul 27, 2011

I am trying to build a survey engine from an existing database design which is like this.

[Code]...

The line Order By Key.RecordOrder throws a null reference exception and I can understand why. Can someone advise on how to resolve this by just modifying this one query? I am fairly new to LINQ and the necessity to write this project

[Code]...

View 1 Replies

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]

View 2 Replies

Linq To Entities Query With Child Objects?

Oct 13, 2011

Basically I have the follwing:Dim ctx As New AdminCoreEntities Dim roles = (From r In ctx.Roles where r.Name.StartsWith("cust") Select r) 'list of System .Linq.IQueryable(Of AdminCoreModel.Role)

[code]...

The error i get when i run this is: Unable to cast object of type System.Data.Objects.ObjectQuery`1[AdminCoreModel.Role] to type AdminCoreModel.Role

Basically I have a many to many situation and I try to get all the Quicklinks objects queried by their roles and not quite sure why EF will cast to a single AdminCoreModel.Role when i.Roles is a collections of objects.

View 1 Replies

LINQ To Objects, Query Arrays In Object?

Sep 15, 2011

I need to query an array. I have tried to use LINQ but with no success.

Here is a simplified structure of Insurance

Public Class Insurance
Public _typ As String
Public _numb As Number()

[Code]....

View 1 Replies

.net - LINQ Query Returns List Of Empty Objects?

May 3, 2012

I have a query that 'selects' object of a type:

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?

View 1 Replies

VS 2010 Dynamically Building LINQ Query To Search Objects

Mar 24, 2011

I am creating a mediaplayer / playlist creator tool that basically imports MP3 songs into playlists (grids). I'm looking to add search functionality where the user can search all open playlists (or a subset of the open playlists). A Playlist is basically a collection of AudioFiles, where an AudioFile is a class that holds the filename of the MP3 file and then exposes the tags (Title, Artist, Album, etc) in public properties.

The idea is that the user can search for a certain expression (for example "the"), and that he can then choose whether to search in the title, in the title and artist, in the title or artist, in the title, artist and/or album, etc. However, I'm having a hard time implementing this and also having it kind of dynamic.

At the moment I am simply gathering all the AudioFiles from the open playlists (or from the subset of playlists the user chooses) and then running a simple LINQ query to find those AudioFiles where the Title contains the search text. Then I display the resulting AudioFiles in a new playlist window:

[Code]....

In case the AND / OR distinguishing is too hard, I would be happy to start with just letting it default to 'OR', so that the user can check Title and Album for example. If he would then search for 'a' then all songs that contain 'a' in their title as well as all songs that contain 'a' in their album should be returned. I guess that makes it easier, but I still wouldn't know how to dynamically create the LINQ query.

View 2 Replies

.net - Group By And Order By?

Mar 24, 2010

using LINQ to NHibernate does anybody know how to use group by and order by in the same expression. I am having to execute the group by into a list and then order this, seem that I am missing soemthing here ?

Example:-

Private function LoadStats(...) ...
Dim StatRepos As DataAccess.StatsExtraction_vwRepository = New DataAccess.StatsExtraction_vwRepository
return (From x In StatRepos.GetAnswers(Question, Questionnaire) _

[code]....

View 1 Replies

Group By And Order By?

Apr 29, 2009

I came across the KEY_GENERATOR thing (as shown below) from one of the tutorial application in vb net. Its absolutely new to me and i wanna know why it is used and how it is used. I googled but didnt find anything about it

View 1 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

.net - VB/C# Group Objects By Key - Performance (memory)?

Dec 8, 2010

I am reading from a log file.My target is to display the 10 most popular requested URL's of a website.One way to do this is to read all log entries and save each URL to a Dictionary. The dictionary has the URL as the Key and the number of visits as the Value. If a URL exists in the dictionary the Value of that URL's Key is increased +1, otherwise a new Key/Value pair is added with a value of 1.

Once the processing is finished the dictionary is sorted by Value and the top 10 entries are shown.This might work, however it could cause a serious memory problem when dealing with a log file of a website which has thousands of different page url's (think query strings).Since I only need the top 10 entries, is there a way to avoid placing all the URL's into memory and still get the top 10 URL + Visits count?

View 3 Replies

Anchor Property Not Working On Two Out Of A Group Of Objects

May 14, 2010

I have a form with a series of basic objects,, a list box a few buttons, a few text boxes and a few labels..

Anchor property works just fine on all of them except one text box and one label. The property is clearly SET on both objects and I can't, for the love of me, figure out what is making these two act "disobediently".

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 - Linq To SQL: Group By And Sum()?

Aug 9, 2010

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).

View 1 Replies

LINQ Group By SUM

May 28, 2012

[code]how can i group by SUM of the c.ct?

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

.NET LINQ Group Joining?

Dec 2, 2010

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 _

[code]....

View 1 Replies







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