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?


.net - Group Join With Multiple Conditions And One Of Them Being With A Constant?

Jan 29, 2010

Here is a snippet of my (VB) LINQ:

From event_evn In xmlEvents.Descendants("event_evn") _
Join genre_gnr In xmlGenre.Descendants("genre_gnr") On event_evn.Element("evn_gnr_id") Equals genre_gnr.Element("gnr_id").Value _
Group Join eventdata_eda In xmlEventData.Descendants("eventdata_eda") On _
eventdata_eda.Element("eda_evn_id").Value Equals event_evn.Element("evn_id").Value And _
eventdata_eda.Element("eda_dty_id").Value Equals "15" _


View 1 Replies View Related

Join With Multiple (OR) Conditions In LINQ To SQL?

Jul 8, 2010

How would I perform this SQL query

Select Distinct s.*
from #ScopeIDs x
Join Scopes s on s.ScopeID=x.ScopeID or x.ScopeID is null

in LINQ to SQL? (This query would return all Scopes whose ScopeID is present in #ScopeIDs, unless one of the entries in #ScopeIDs is null, in which case it returns all Scopes).

A "literal" translation doesn't work, since LINQ doesn't support joining with multiple conditions - code along these lines ...

From x in ScopeIDs
Join s in Scopes on s.ScopeID equals x.ScopeID or x.ScopeID equals nothing
Distinct Select s
... doesn't compile.

View 1 Replies View Related

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


View 5 Replies View Related

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


View 4 Replies View Related

Linq - Group By Multiple Columns?

Dec 6, 2011

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:


View 1 Replies View Related

LINQ Group By With Multiple Properties?

Jun 10, 2011

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},


View 3 Replies View Related

Linq Group On Multiple Fields - Anonymous - Key

Apr 3, 2012

I am stumped. I have a DTO object with duplicates patient address data. I need to get only the unique addresses.


View 3 Replies View Related - 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.


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


View 1 Replies View Related

Group Joins With Multiple Tables Converting SQL To Linq

Mar 7, 2011

Can anyone help me by translating this SQL Statement to Linq? [code]

View 1 Replies View Related

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]
SELECT TOP (1) [t5].[Latitude]


but this produced an error: "A group by expression can only contain non-constant scalars that are comparable by the server."

View 1 Replies View Related

Linq - Order By Multiple Columns Using Lambda Expressions

Nov 16, 2009

I'm still trying to get my head around the whole "Lambda Expressions" thing.

Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?

Here is my existing code, which returns an ordered list using a single-column to order the results:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList

Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.

I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList

View 2 Replies View Related

Table - Group Filter Conditions In ReportViewer ?

Mar 21, 2011

How can I combine the filter conditions in a Table in ReportViewer? Here is a screenshot [URL]

I want to do like this;

if (Expr3.Value = 0) or (Expr3.Value = 3) or (Expr3.Value = 6) or (Expr3.Value = 4 and Vadeli.Value = True)

View 1 Replies View Related

LINQ Group By Multiple Values Does Not Work Well But Work Well In C#

May 29, 2012

I found that when group by multiple values does not work well with VB.NET, but it works well with C# ,here are my code, is there something wrong with my VB.NET Code? Here is my VB.NET code:


View 1 Replies View Related

Sql - Dynamically Varied Number Of Conditions In The 'where' Statement Using LINQ?

Feb 3, 2010

I'm working on my first project using LINQ (in mvc), so there is probably something very simple that I missed. However, a day of searching and experimenting has not turned up anything that works, hence the post.

I'm trying to write a LINQ query (Linq to SQL) that will contain a multiple number of conditions in the where statement separated by an OR or an AND. We don't know how many conditions are going to be in the query until runtime. This is for a search filter control, where the user can select multiple criteria to filter by.

select * from table
where table.col = 1
OR table.col = 2
OR table.col = 7
'number of other conditions

Before I would just construct the SQL query as a string while looping over all conditions. However, it seems like there should be a nice way of doing this in LINQ. I have tried looking using expression trees, but they seem a bit over my head for the moment. Another idea was to execute a lambda function inside the where statement, like so:

For Each value In values matchingRows = matchingRows.Where(Function(row) row.col = value)However, this only works for AND conditions. How do I do ORs?

View 3 Replies View Related

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


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


View 1 Replies View Related

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

Multiple WHERE Conditions SQL Update

Feb 15, 2012

I'm doing a stock Control System as a school Project using An Access 2007 DB and Visual Studio 2010. I'm trying to do an update Query based on two variables entered into comboboxes, I cannot get the VB to accept the conditions for this, Can anyone Help me?[code]I Cannot get the Code to recognise the Last "'", is there a way to do this?

View 7 Replies View Related

Using Multiple Conditions In The Same For Loop?

May 7, 2010

i want to set 2 conditions for a for loop as i want to loop through the same line of code at the same time . here it is as i have it now

it does not work how i want it to as i want both loops to run simuntaneously instead it runs the first loops continuously before the second and way around this?

For Me.i = 0 To maxrows - 1
For Me.h = 1 To maxrows
Me.Controls.Item("TextBox" & Me.h).Text =


View 1 Replies View Related

Multiple Conditions With A SELECT From Where Query?

Mar 30, 2010

I am trying to link to a Access database at runtime using a SELECT FROM WHERE query, which I can do but.......

with the WHERE part I want to select several conditions, 4 actually and it is not working, what am I doing wrong?

Here is my code,

Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=V:GYMDBFLineProdSanderProduction.mdb")


View 2 Replies View Related

VS 2008 Multiple If Not Conditions On One Line?

Apr 15, 2010

How can I have multiple If Not conditions on one line?

Here are the combinations that I've tried, but they either don't work, or won't build.

If Not (txtDisplay.Text = "0") And If Not (txtDisplay.Text = "")


View 3 Replies View Related

Access - JOIN Two Tables With Multiple WHERE Conditions

Jun 21, 2010

I have two tables 1) tblRequests and 2.) tblMainTags. The Fields in tblRequests are Tag_Request_No, Employee_ID , Accepted, Accepted_Date, and Accepted_Time. The Fields in tblMaintags are Tag_Request_No, Tag_ID, Completed, ... The fields 'Accepted' and 'Completed' are set to YES/NO.


View 5 Replies View Related

Forms :: Managing Multiple Conditions In IF - Then Statement

Oct 19, 2010

I currently have an If...Then statement that checks if all fields of a form have been filled before saving the info in a file. I'd like to be able to tell which field has not been filled to give the user a dynamic message (at the moment, it only tells them that the checklist is not completed ) :

If (txtNoDemande.TextLength = 8 _
Or txtNoDemande.TextLength = 13 _
And txtDateLoad.TextLength <> 0 _


Is there a way to determine which of these conditions is false without having to do a seperate If statement for each ?

View 2 Replies View Related

VS 2008 Creating A SQL Statement With Multiple WHERE Conditions?

Feb 27, 2010

I am trying to write a Function which will return a data table, filled with a data from a database.

The Function will accept 6 diffrenet parameters as Optional. Each one of them will be an additional condition to be added to a where clause, if it`s provided when the function is beeing called.

Is there any method in .NET to simply add a new condition to the where clause?

View 10 Replies View Related

VS 2010 - Multiple Conditions For Select Case

Jun 26, 2010

I'm programming a utility for a game, and at the moment I am adding chat commands for it. They use the Select Case type, but I want to be able to use multiple conditions for 1 case.

Case "/lame"
If sParameter = "announce" Then
AnnounceMsg("^1No Laming
^7Laming consists of
^5* ^7Attacking someone with
^5- ^7Weapon Down
^5- ^7Chatbubble Up")
[Code] .....

I get an error:
Conversion from string "/lame" to type 'Long' is not valid.

View 7 Replies View Related

"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) = _


View 1 Replies View Related

How To Make A Statement Run If All Conditions Are True From Multiple Condition Or If Statements

Mar 22, 2011

I have a form that contains multiple conditional or if statements on several defferent for controls.

Example: Radio Buttons, TextBoxes and CheckBoxes.

I am intending to create an order form(demo) where the user can select multiple products.

I have a default order number that changes  by one everytime an order is successful.

An order is only successful if all the information on the form is entered correctly.

My question is where do I insert the code for the order number?

Basically for the order number I have a counter that count by increment of one if an order is successful.

Meaning when the user hit place order, and all the infromation is right, then the order numer goes to 1 from zero.

Where do I add the condition for the order number since all the fields must first be completed.

Do I have to create a whole line of if else statements?

View 5 Replies View Related - 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 web form:

Dim db As New MeetingManagerDataContext
Dim q = From s In db.vwRoomAvailabilities _
Where s.MeetingID = lblMeetingID.Text _


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


May 28, 2012

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

View 1 Replies View Related

.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


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 _


View 1 Replies View Related

C# - LINQ To SQL Group People By Age?

Nov 3, 2011

Sample in C# and VB.NET are OK.

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.

View 4 Replies View Related

C# - Using LINQ To SQL Group, Sum And Aggreate All Together

Aug 18, 2010

I have two tables Students and Origami. Origami has Foreign Key of Students table. Each student can make one or more origami for each month.


This query give only total origami of each student. But I want monthly count of origami for each student.

View 2 Replies View Related

Linq InvalidCastException For Group By

Dec 12, 2010

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 _


I don't like working with anonymous types so I'm trying to delare the result and am hitting an InvalidCastException.

Here's the type information:



View 2 Replies View Related

Linq InvalidCastException For Group By?

Aug 12, 2011

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.

Here's the type information:




and the inner type:




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


View 4 Replies View Related

Using Linq Group Joins In .Net?

Oct 18, 2011

I'm trying to figure out how to use Group Joins in LINQ queries under 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.

View 2 Replies View Related

VS 2010 LINQ To SQL Group By?

Nov 16, 2011

In proper sql my query would be something like:

select,, count(
from cats c, items i


View 1 Replies View Related

Linq Doing A Group In A Lambda Subselect

Feb 23, 2012

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

View 1 Replies View Related

C# - Pick Out A Group Of Items Using Linq To Xml

Jul 4, 2011

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.


View 1 Replies View Related

Get A Linq To Sql Group By Query Into The 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 Ascending _


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

Linq Group Count Items?

Dec 5, 2011

I have this linq to entity

From r In ReceiptRepository.Fetch
r.RECEIPTDATE >= ReportStartDate And


This is working fine, except the count property, it is just giving the number of group count. I don't know how to find out each Tender Count

View 1 Replies View Related


Jan 15, 2009

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


View 5 Replies View Related

Sql - LINQ Group By Aggregating The Rows In .net?

May 10, 2012

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.


View 2 Replies View Related

VS 2008 - LINQ Group By Datatable

Feb 21, 2012

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.

View 4 Replies View Related

Can't Use A Where Clause On Both Tables In A LINQ Group Join?

Jun 7, 2011

Here's what I want to do:

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?

View 1 Replies View Related

Group By Over Anonymous Type With Linq To Object?

Feb 25, 2010

I'm trying to write a linq to object query in, here is the c# version of what I'm trying to achieve (I'm running this in linqpad):

void Main()
var items = GetArray(


View 1 Replies View Related