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


ADVERTISEMENT

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

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

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

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

Decimal And Double Precision

Jun 30, 2009

I am working on an application that allow the user to store data as numbers.These numbers are later on used for calculation. The number can be of any type and are saved as string. The problem is when they are used for calculation how can understand when it is better to treat them as doubles and when as decimals?

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

Use Numbers With A Precision Of Hundreds Of Decimal Places?

Mar 21, 2011

I want to use numbers with a precision of hundreds of decimal places.

I know of the BigInteger datatype for ints, but System.Numerics falls short beyond the decimal.

How can I achieve anything beyond a simple Decimal/Double precision in vb.net?

View 2 Replies

Change A Double To A Precision Of 2 Places To The Right Of Decimal Point?

Nov 22, 2009

how to get 1.83333333333... to 1.83?

Dim temp_1 As String
temp_1 = 5.50 / 3

Label1.Text = String.Format(temp_1, "{0.00}")

View 4 Replies

RoundUp Function - Which Will Round A Number UP To The Specified Decimal Precision

Apr 29, 2009

I need a function which will Round a number UP to the specified decimal precision, exactly the same as how Excel's RoundUp function works:

Roundup(dblVal, intDecPlaces)

So I need the following:

Roundup(0.896523, 4)
would return
0.8966

However, everything i've tried/found simply rounds to the nearest whole integer, or returns a normal rounded value, hence the above would return
0.8965

I've tried the following:

Math.Round(dblval, intPrecision, midpointrounding.awayfromzero)
' and
Math.Round(dblval, intPrecision, midpointrounding.toeven)

And even custom functions, such as:

Public Function RoundUp(ByVal varValue As Object, _
ByVal iNum As Integer) As Double

'ignore the data types here, I was playing to see 'if changing any of the data types would swing 'the results (knowing full well they wouldnt make 'a difference, thats how fed up with this I am!)

Dim lNum As Long, xVal As Double, xVar As Object

xVar = Fix(varValue)

[CODE]...

I've even looked at converting this to a string, looking at the Xth decimal place, and incrementing it up by 1, then converting it back to a double, while this works (sort of) it seems to be a very roughshod way of doing it, and I'd rather do it mathematically than with lots of data conversion.

View 6 Replies

C# - Adding Two .NET SqlDecimals Increases Precision?

Jun 23, 2011

in .NET, when I add two SqlDecimals, like so:

[Code]...

then s3 has precision 2, whereas both s1 and s2 have precision 1. This seems odd, especially as the documentation states that the return value of the addition operator is "A new SqlDecimal structure whose Value property contains the sum." I.e. according to the documentation, addition should not change the precision.

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

When Adding A Value To Another Value The Results Eventually Change From 2-decimal Places To Multiple Decimal Places?

Mar 13, 2009

Problem: Using the sub routing below, when adding a value to another value the results eventually change from 2-decimal places to multiple decimal places.Basically, the amount stored should always only be 2 decimal places, because the values passed in are always 2 decimal places. Output from calling the sub routine multiple times.

Running total = 329430.75
New Withheld Amount = 710.79
Running total = 330141.54

[code]....

As a workaround, I have a new routine that uses a custom round function to properly store only 2 decimal places - as the VB round function does not perform the type of rounding desired.I understand that we are removing the value from the dictionary and adding it back..

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

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

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.

[code]...

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

View 2 Replies

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 _

[Code]...

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:

Debug.Print(query.GetType.ToString)
Returns:
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]]]

[Code].....

View 2 Replies

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:

Debug.Print(query.GetType.ToString)

Returns:

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]]]

and the inner type:

Debug.Print(item.GetType.ToString)

Returns:

VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]

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

[code]....

View 4 Replies

Using Linq Group Joins In .Net?

Oct 18, 2011

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.

View 2 Replies

VS 2010 LINQ To SQL Group By?

Nov 16, 2011

In proper sql my query would be something like:

select c.id, c.name, count(i.id)
from cats c, items i
where c.id=i.catid

[code].....

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

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
[code...]

View 1 Replies

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.

[Code]...

View 1 Replies

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:

[Code]...

View 1 Replies







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