Develop Reference
Csharp xcode actionscript-3 hibernate grails.
Why can't I assign a value to a decimal with a ternary operator? - c#

I have a list of objects (using anonymous types) containing a decimal and an integer ID, and I'm building a function to take the sum of the decimals contained within all unique objects in the list. This is the line of code I wrote: var result = (objectList.Any()) ? objectList.Distinct().Sum(x => x.DecimalValue) : 0; However, it always returns a decimal with the value 0, even though it should be returning the sum - objectList contains five identical objects in my example, so it should return the DecimalValue. If I replace it with these two lines of code, however, it returns the DecimalValue: decimal result = 0; if (objectList.Any()) result = objectList.Distinct().Sum(x => x.DecimalValue); Why does the second set of lines work, but the first line returns the wrong value? objectList.Any() is true, so it shouldn't be using the false assignment. Update: I generated the list of anonymous types using this line of code: var objectList = _ms.Read(cmd, x => new { DecimalValue = x.Field<decimal>("SomeColumnName"), Id = x.Field<int>("SomeColumnId") }).ToList(); _ms is a DAO for MS SQL, and it's running the lambda function that converts each datarow of the results to the anonymous typed object, which is returned in a list. I actually haven't been able to figure out how to build a list of those objects manually. Another Update: Using Reed Copsey's reply below, I created the list manually in a way that duplicates the list that I'm getting, and I can reproduce the error with the manually created list: var objectList = Enumerable.Range(0, 5).Select(i => new { DecimalValue = (decimal)31.45, Id = 3 }).ToList(); var result = (objectList.Any()) ? objectList.Distinct().Sum(x => x.DecimalValue) : 0; I also tried removing the cast to decimal, and the issue is still present. Another Update: After some further debugging I realized something I've never come across before. I set a breakpoint immediately after the line of code I mentioned that was having problems in each case. For the workaround, it returned 31.45. For the problem line, it returned 0. When I stepped into the next line, and looked at the variable again, it said 31.45. The line I set the breakpoint on did not access or modify the variable. It would seem that both lines work, but that the debugger showed that it did not until I moved at least two lines after the code. I've never come across that before, but it shows that the code indeed does work.
There is no problem with your statement. the issue is elsewhere, most likely in how you're constructing objectlist. for example, the following works exactly as expected, and prints "0.6" (as would be expected): namespace test { using system; using system.linq; internal class testcompile { private static void main(string[] args) { var objectlist = enumerable.range(0, 3).select(i => new { id = i, decimalvalue = i / 5.0m }).tolist(); decimal result = objectlist.any() objectlist.distinct().sum(x => x.decimalvalue) : 0; console.writeline(result); console.readkey(); } } } update: in response to your update, this also works perfectly: private static void main(string[] args) { var objectlist = enumerable.range(0, 5).select(i => new { decimalvalue = (decimal)31.45, id = 3 }).tolist(); var result = (objectlist.any()) objectlist.distinct().sum(x => x.decimalvalue) : 0; console.writeline(result); console.readkey(); } it is using the exact code you pasted, and reports 31.45, as expected (due to the unique constraint). note that, personally, i would use 31.45m instead of the cast, but it works even as written..., for what it's worth, your code works though i had to make up my own type. [test] public void x() { var objectlist = enumerable.range(1, 10).select(d => new {decimalvalue = convert.todecimal(d)}); var result = (objectlist.any()) objectlist.distinct().sum(x => x.decimalvalue) : 0; assert.areequal(55, result); assert.areequal(typeof (decimal), result.gettype()); } too big for a comment so cw it is., i just compiled a code public class objectvalue { public decimal decimalvalue { get; set; } } class program { static void main(string[] args) { var objectlist = new list<objectvalue>() { new objectvalue() { decimalvalue = 5 }, new objectvalue() { decimalvalue = 5 } , new objectvalue() { decimalvalue = 5 }}; var result = (objectlist.any()) objectlist.distinct().sum(x => x.decimalvalue) : 0; decimal resultdecimal = 0; if (objectlist.any()) resultdecimal = objectlist.distinct().sum(x => x.decimalvalue); } } and result and resultdecimal are 15, in my case. i have coherent result in both cases provided, as i expected. so the error is somewhere else., i need to compare two very large collections with potentially missing elements, cannot use a lambda expression as an argument to a dynamically dispatched operation, update a variable inside foreach loop, easy way to select more than one field using linq, simple way to read integers from a file.
- Encrypt Message
Copyright © 2018 www.developreference.com
% cannot be assigned to decimal type C#
I have a data type of type decimal.
I want to carry out following:
But it is giving me the above error.
Following should help you with decimal.
A "real literal" without suffix or with the d or D suffix is of type double. You could read more on suffix here
- Suffix for Decimal - M or m
- Suffix for float - F or f
- Suffix for Double - Without any suffix or D/d
Collected from the Internet
Please contact [email protected] to delete if infringement.
Click to generate QR
- Share to Weibo
- Copy to clipboard
a value of type struct cannot be assigned
Nil cannot be assigned to type avcapturedeviceinput, networkimage cannot be assigned to type widget, a value of type "int" cannot be assigned to an entity of type "node<int> *"c/c++(513), argument type cannot be assigned to the parameter type, operator && cannot be applied to operands of type decimal and decimal, cannot convert type decimal to double, left side cannot be assigned for a record type, argument of type "series[dtype]" cannot be assigned to parameter of type "dataframe", intellisense: a value of type "void" cannot be assigned to an entity of type "double", arraytypemismatchexception: source array type cannot be assigned to destination array type, error : the argument type int cannot be assigned to the parameter type string, a value of type int cannot be assigned to an entity of type node, error: value of type "void *" cannot be assigned to an entity of type "int **", const data type cannot be assigned into a non-const data type, value of type "const char *" cannot be assigned to an entity of type "lpstr", a value of type const char* cannot be assigned to an entity of type char*, error: a value of type "double*" cannot be assigned to an entity of type "double", a value type of double cannot be assigned to value type of double,, angular | the argument of type 'user[]' cannot be assigned to the parameter of type 'expected<user>', cannot implicitly convert type 'string' to 'decimal', operator '<' cannot be applied to operands of type 'decimal' and 'double', operator '<' cannot be applied to operands of type 'double' and 'decimal', error cs0019: operator '<=' cannot be applied to operands of type 'double' and 'decimal' in c# console app, mongo_dart error: a value of type 'rational' can't be assigned to a variable of type 'decimal', list<list<>> cannot be assigned to list<list<>> when type parameter is involved, property or indexer of type repeatedfield cannot be assigned to — it is read only, a null value cannot be assigned to a primitive type error (spring/hibernate), the final local variable dc cannot be assigned, since it is defined in an enclosing type, related related.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Assigning a decimal value to an individual employee c#
Im currently making a payroll system. I have like 5 or 6 employee's and each of them has a different hourly rate, how would I assign an hourly rate to each individual?!
At the moment I have something along the lines of(Which is incorrect)...
- 1 You have to acces the elements by index, for example: employeeID[0]=="Brian", see for loop and arrays ... – EugenSunic Jul 30, 2015 at 22:32

3 Answers 3
Try this code:
Always use a loop to go through all elements in array, and access them by index. When populating, modifying elements, always use a loop.
I guess it's very likely you will need to assign other things to your employees (Ex: Hours done in the week, address, etc.) so instead of mapping everything in a dictionary or an other array, make a Class to hold your employees information:
With a class you can keep your model extensible and if you need to save that information somewhere, it's easy to serialize it or map it to a DB table.
You can keep all your employees in a list. To initialize them with a value, you do this:
To set the info at a later stage, simply get the employee with the corresponding ID and set its hourly pay:
You could create a dictionary,
Or in a more compact edition , using a collection initializer:
Using a dictionary, it's also the most efficient way to get later the hourly rate of each employee, by using the employeId. It's an O(1) operation.
If you don't like this approach, you could declare a class called Employee, like below:
Then instead of having an array with the employees ids, you could define an array of Employee objects.
This way each time you create an employee you have to provide an Id and a hourly rate.
How would I display my results?
Since you picked the solution of the class, I would opt to overload the ToString method.
So, when you call for instance employees[0].ToString() , you get the following string:

- Okay using a class worked for me well thanks! How would I display my results?! I have a textbox which displays the employee's name, hourly wage, tax, net pay etc. I originally had uiResults.Text = "Staff Name": "; uiResults.AppendText(employeeID).ToString()); Etc. Im unsure how I can display the employees and pay onto the text box (Sorry for the question, im reletively new to C#!) – TheBiz Jul 30, 2015 at 23:33
- Generally these would be displayed in separate controls. If you need it to be displayed in one field, you could use format => uiResults.Text = string.Format("Staff Name: {0}. Pay: {1}\r\n", employee.Id, employee.HourlyRate.ToString("C")); where employee is an instance of Employee – AWinkle Jul 30, 2015 at 23:55
- @Biz94 You are welcome. I am glad that I helped. Please see my update. – Christos Jul 31, 2015 at 4:48
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c# string decimal or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Linear regulator thermal information missing in datasheet
- Linear Algebra - Linear transformation question
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- Biodiversity through radiation
- How can I check before my flight that the cloud separation requirements in VFR flight rules are met?
- How can this new ban on drag possibly be considered constitutional?
- Styling contours by colour and by line thickness in QGIS
- How to handle a hobby that makes income in US
- Can I tell police to wait and call a lawyer when served with a search warrant?
- Why is there a voltage on my HDMI and coaxial cables?
- nicematrix: controlling column spaces
- Lots of pick movement
- Is it possible to rotate a window 90 degrees if it has the same length and width?
- Identify those arcade games from a 1983 Brazilian music video
- Is the God of a monotheism necessarily omnipotent?
- Batch split images vertically in half, sequentially numbering the output files
- Whats the grammar of "For those whose stories they are"?
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Do "superinfinite" sets exist? That is, sets equivalent to a proper subset via an all-structure-preserving bijection.
- Are there tables of wastage rates for different fruit and veg?
- How to notate a grace note at the start of a bar with lilypond?
- Replacing broken pins/legs on a DIP IC package
- How do you get out of a corner when plotting yourself into a corner
- Can Martian regolith be easily melted with microwaves?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
c# node.js objective-c powershell svn
Can an array of decimal values be assigned to a List of integers - c#
Is is possible to assign an array of decimal values to a list of integers? Let's say I have an array like decimal[] decemalNumbers and a list of integers like List intNumbers. So can I do the assignment like intNumbers = decemalNumbers.ToList()? How Can I do an explicit conversion? Is it possible?
A simple linq solution: decimal[] decimalnumbers = {1.11m,5.22m,3.25m,4.66m,9.13m}; list<int> integernumbers = decimalnumbers.select(x => convert.toint32(x)).tolist(); output: integernumbers[0]=1 integernumbers[1]=5 integernumbers[2]=3 integernumbers[3]=5 integernumbers[4]=9, try like this , to convert it to int // obj is decimal array or list ienumerable<int> result = obj.select(d=> decimal.toint32(d));, convert list of double to list of integer in c#, dictionary has enum as value. how can i extract an int[] array (since enums are “ints”), how to convert list of objects with two fields to array with one of them using linq, list box conversion to array int, json to c# : convert an arraylist of doubles to an array of ints.
- Encrypt Message
Copyright © 2018 www.develop-bugs.com

IMAGES
VIDEO
COMMENTS
Why can't you assign a number with a decimal point to the decimal type directly without using type suffix? isn't this kind of number considered a number of type decimal?
I have like 5 or 6 employee's and each of them has a different hourly rate, how would I assign an hourly rate to each individual?! decimal hourlyPay = 0.0M; if (employeeID == "Brian") { hourlyPay = 8.00M; } Thanks!
decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0 or decimalVar.ToString ("0.##"); // returns "0" when decimalVar == 0
I have like 5 or 6 employee's and each of them has a different hourly rate, how would I assign an hourly rate to each individual?! decimal hourlyPay = 0.0M; if (employeeID == "Brian") { hourlyPay = 8.00M; }
I have a list of objects (using anonymous types) containing a decimal and an integer ID, and I'm building a function to take the sum of the decimals contained within all unique objects in the list
I am using conversion to decimal of a byte array, such that it contains either null or any other number, stored in byte. The problem here is, when I try to convert a null to Nullable decimal, it converts it to zero
I have a data type of type decimal. I want to carry out following:if(decimalData % 0.25 !=0) { //do some manipulation }. Following should help you with decimal
I have like 5 or 6 employee's and each of them has a different hourly rate, how would I assign an hourly rate to each individual?!
Is is possible to assign an array of decimal values to a list of integers? Let's say I have an array like decimal[] decemalNumbers and a list of integers like List intNumbers