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.

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

Click to generate QR

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.

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

TheBiz's user avatar

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.

Lachlan Goodhew-Cook's user avatar

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:

Pierre-Luc Pineault's user avatar

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:

Christos's user avatar

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 .

Hot Network Questions

assign 0 to decimal c#

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.

Copyright © 2018 www.develop-bugs.com

IMAGES

  1. c#

    assign 0 to decimal c#

  2. Regex Decimal Validation in C# Java

    assign 0 to decimal c#

  3. Program in C and C++ to Convert Decimal number to Binary, Octal and Hexadecimal number Using

    assign 0 to decimal c#

  4. C# Decimal

    assign 0 to decimal c#

  5. Java for Testers

    assign 0 to decimal c#

  6. Solved Write a loop that subtracts 1 from each element in

    assign 0 to decimal c#

VIDEO

  1. Load Records from Database in C# Windows Form for Update

  2. Kanjoos girlfriend be like #trendingshorts #funnyvideos #comedy #youtubeshorts #viralvideo

  3. C++ programming, displays all odd numbers from 1 to 100, or any number

  4. Pres. Marcos Jr. to assign DA chief at the right time, to remain DA secretary for now

  5. write a C-program to display numbers between 1-100 which are divisible by 5 and 7 |Toos learning |Ak

  6. C PROGRAM TO COUNT THE NUMBER OF DIGITS BEFORE AND AFTER THE DECIMAL POINT

COMMENTS

  1. c#

    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?

  2. Assigning a decimal value to an individual employee c#

    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!

  3. assign decimal value c# Code Example

    decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0 or decimalVar.ToString ("0.##"); // returns "0" when decimalVar == 0

  4. Assigning a decimal value to an individual employee c#

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

  5. Why can't I assign a value to a decimal with a ternary operator?

    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

  6. Assign null to decimal using ternary operator

    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

  7. cannot be assigned to decimal type C#

    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

  8. string

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

  9. Can an array of decimal values be assigned to a List of integers

    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