The problem is that in c# I can't subtract the objects, so I need to figure out how to get the integers out of them and then do the arithmetic? Here's the code.. what am I missing?
dsfDataSet.itemTotals.Compute( "SUM(priceSum)", String.Empty ) - dsfDataSet.discountItems.Compute("SUM(totDiscount)", String.Empty)
If you know the data is integer, you should use Convert.ToInt16 or similar functions to extract the integers. Be sure to add additional exception handling, in case the data turns out to be non integer.
you can use int.TryParse as the output of DataTable.Compute is object
int priceSum,totDiscount;
if(int.TryParse(dsfDataSet.itemTotals.Compute( "SUM(priceSum)", String.Empty ).ToString(),out priceSum))
{
if(int.TryParse(dsfDataSet.discountItems.Compute("SUM(totDiscount)", String.Empty).ToString(),out totDiscount))
{
priceSum - totDiscount;
}
}
What is the return type of your Compute function? Object? Or a defined type?
If defined, you CAN overload the '-' operator, you know?
Otherwise, what is stopping you from creating a method that take those two structures and return the integer result you need? Why must it be with '-' ?
Related
I want to perform an AND operation. My inputs are 2 objects. It could be a string like "true" or it could be an expression like "1==1" as well. When using && operator, am getting an exception that String was not recognized as a valid boolean.
Please help me.
return Convert.ToBoolean(obj[0]) && Convert.ToBoolean(obj[1]);
Sorry for the earlier post which was not clear enough.
Converting "1==1" to a boolean is not possible for the Convert.ToBoolean method. It just converts the strings true and false.
You will have to either write a expression evaluator yourself, or use some kind of library to parse your string to a boolean (like Flee for example)
First make sure obj[0], obj[1] will only contain 1 or 0(char or integer).
Because Convert.ToBoolean does not understand anything other than 1 or 0.
The below one will work
Convert.ToBoolean(true) && Convert.ToBoolean(1==1)
Why use a string?
The conversion will not evaluate code, it will check if the supplied data is possible to convert to a bool and do so if possible.
Your function will always return true if it was working, cause 1 is always equal to 1, and true is always true.
This is nearly impossible as C# is strongly type language.
What you trying to do is for weakly types languages like JS. "1==1" will work for JS, not for C#.
Remove quotes in order to make it work(You might as well remove first operand, as it doesn't make any sense):
return ( 1 == 1 );
I am getting the error "System.FormatException : input string was not correct".
TextBox2.Text = objnm.rupees(Convert.ToInt64(Convert.ToDecimal(txtWOrds.Text.Trim())));
First, you don't need to convert it to decimal (Convert.ToDecimal) and then to Int64 (Convert.ToIn64).
Second, if txtWOrds.Text is not a number or is empty, than you will get this exception. Make sure that it is a number.
Third, if your value is a number, than your problem likes somewhere in objnm.rupees()
You should check the input in case its empty, like string.IsNullOrEmpty(txtWOrds.Text) then proceed with the parsing of the contents of the textbox.
Also you should be using TryParse which evaluates if the text can be parsed and if true you can use the value of the out parameter of this method.
In your case it could fail if the TextBox is empty.
Also if its anything related to money/currency not sure if you need the conversion to Long (seems like a mismatch there, please clarify. If you want a specific set of decimal points then it would be better to use decimal.Round )
Decimal value = default(decimal);
bool isValid = decimal.TryParse(txtWOrds.Text.Trim(), out value);
if (isValid)
{
//your code using output 'value'
}
Remove Convert.Int64 and just use Convert.ToDecimal (ideally you should use decimal.TryParse). Also, ensure that the input textbox contains the correct type (a decimal)
In my code I have an arraylist, called heart, which contains numbers from 1-13.
heart.Add("any");
for(int i = 0; i < 14; i++)
{
heart.Add(i);
}
As you can see it also contains "any" placed in the first element. When I use this code to get the all of the elements that has a value over 5 I get an error.
int store = heart.Cast<int>().Where(item => item > 5).Count().ToString();
I get the error "Specified cast is not valid" and that's because of the
"any" I have in the first element. Could anyone help me fix this?
It sounds like you just need the OfType method instead:
string store = heart.OfType<int>().Where(item => item > 5).Count().ToString();
OfType only returns values which are of the approriate type, ignoring others. See my Edulinq blog post on it for more information.
As Sven shows, you can also use the overload of Count which takes a predicate, to remove the Where call:
string store = heart.OfType<int>().Count(item => item > 5).ToString();
(I've changed the variable type given that you're calling ToString at the end... again, you may want to think about this decision. It depends on how you're using it of course.)
However, I'd strongly advise you to use a strongly-typed collection instead of ArrayList. Think about what the collection is meant to hold - it seems odd to hold both strings and integers. What are you trying to do with it?
Use this instead:
int count = heart.OfType<int>().Count(item => item > 5);
OfType will filter the list and return only those elements that are the correct type, rather than Cast which tries to cast all elements.
You can't cast the word "any" to an integer, that's pretty straight forward.
We'd have to know exactly what your trying to do with here, and how the array is used to really give a good recommendation.
Since you're using int and you wanted values of 1-13, may I suggest you use an int value of 0 to represent 'any'?
You could do
Int store = heart.GetRange(1, heart.Count - 1).Cast<int>().Where(item => item > 5).Count().ToString();
I just need to know if the value is numeric. I don't need to do anything with the value. Is this the best way? Feel dirty creating a variable that I won't ever use beyond this:
int val;
if(int.TryParse(txtFoo.Text, out val))
{
....
}
Yes, using the relevant TryParse method and ignoring the out parameter is the best way of doing this.
You may want to wrap this up into your own set of helper methods (which could specify the appropriate culture etc, if the default isn't right for you) and just return a bool without the out parameter to make them easier to call.
Of course, you need to work out what kind of parsing is most appropriate - even for integers, you need to consider whether the range of Int32 is enough for your use case. In my experience, most numeric input has its own "natural" range of valid values, which is unlikely to be exactly the range of any predefined type. You may therefore want to expand your helper methods to include the range of valid values to accept.
"is numeric" is an ambiguous term.
Culture-aware?
Allow thousands and/or decimal separators?
Allow scientific notation?
Allow a sign (before? after?...)
What range of values do you allow? Signed 32-bit integer (Int32.TryParse), Unsigned 32-bit integer (UInt32.TryParse), decimal, double, ...
Hence there is no "best" way, and the Framework provides a multitude of different ways to parse numbers.
You can use Regular expressions
Regex _isNumber = new Regex(#"^\d+$");
_isNumber.IsMatch(txtFoo.Text);
This will only match Ints, but you can write one that also matches decimals.
It's not as flexible as int.TryParse, but you could check to see if each character is a number:
bool isInt = txtFoo.Text.All(c => char.IsNumber(c));
In general, though, I would recommend sticking with int.TryParse. You can even call the unused parameter "ignored" to be explicit about your intent, e.g.:
int ignored;
bool isInt = int.TryParse(txtFoo.Text, out ignored);
That is the recommended way of doing it in C#. However, you could also add Microsoft.VisualBasic.dll as a reference to your project and then use Microsoft.VisualBasic.Information.IsNumeric()
You can try using Regex parsing to determine that there are no non-numeric characters in a string, or you can use Int.TryParse(), Double.TryParse(), Float.TryParse() depending on the input.
bool test (string teststring)
{ for (i=0;i==teststring.length;i++){
if instr("0123456789.,-+Ee",teststring.substring(i,1) <0){return false;}
// some additional tests below here if you like
return true;
}
however E1001E12e.12e would be noted as a number a little bit more magic is needed to do a clean check, but then you might be able to determine if its a int or a float too..
That's the best way of doing it in my knowledge - that's what our company standards adhere to anyway due to the error handling being done within the parsing.
This details the advantages: https://web.archive.org/web/20150510214425/http://www.dotnetperls.com:80/int-tryparse
attrval[5] = WrmService.WindowsAgent.AgentVersion;
From above if attrval[5] is null or not getting any value or any strings other than numeric values I want to assign attrval[5] to value '0.0.0.0' otherwise I will
display the numeric value which is coming.What coding i have to implement here
as per the information while doing googling I did this
attrval[5] = (WrmService.WindowsAgent.AgentVersion == null || Microsoft.VisualBasic.Information.IsNumeric(WrmService.WindowsAgent.AgentVersion)) ?
"0.0.0.0" : WrmService.WindowsAgent.AgentVersion;
but Microsoft.VisualBasic.Information.IsNumeric making problems. Is there any similar one in C#?
only two outputs I required one will be numeric and one will be any other, it can be string or null whatever it i have to set in to 0.0.0.0
Try
if(!int.TryParse(WrmService.WindowsAgent.AgentVersion, out attrval[5])) attrval[5] = 0;
In this case, if AgentVersion is numeric, it will place the parsed value into attrval[5], otherwise it will set it to 0.
edit
Ah I guess you are looking for:
attrval[5] = string.IsNullOrEmpty(WrmService.WindowsAgent.AgentVersion) ? "0.0.0.0" : WrmService.WindowsAgent.AgentVersion;
I would recomend using something like
Int32.TryParse Method (String, Int32)
See also C# Equivalent of VB's IsNumeric()
You could use Int32.TryParse() to check if it is an integer value.