0

I have the following code inside my asp.net vmc web application :-

var getNumbers = (from t in ut.newTag
                                where char.IsDigit(t)
                                select t).ToString();
            tech.PartialTag = Convert.ToInt32(getNumbers);

but i am getting the following exception :-

Input string was not in a correct format.

so can anyone advice how i can solve this issue??

6
  • what's your input then? Commented Dec 19, 2013 at 17:05
  • What is the value of getNumbers ? Commented Dec 19, 2013 at 17:06
  • it refer to the getNumbers Commented Dec 19, 2013 at 17:06
  • Two steps: First, what is ut? Next, what does getNumbers get set to? Commented Dec 19, 2013 at 17:06
  • @n8wrl ut.NewTag is a string Commented Dec 19, 2013 at 17:07

2 Answers 2

5

getNumbers is a string, containing type name of string enumerator It will look like

"System.Linq.Enumerable+WhereSelectArrayIterator`1[System.String,System.String]"

You obviously can't convert that type name to integer. If you want to try parse newTag and assign it to PartialTag if there is an integer:

int value;
if (Int32.TryParse(ut.newTag, out value))
    tech.PartialTag = value;
Sign up to request clarification or add additional context in comments.

4 Comments

+1: Unless OP wants to ignore non-digits altogether TryParse is much more readable alternative to strange LINQ expression (even Regular expression would be more readable and expected in validation code).
@AlexeiLevenkov thanks :) Just want to add, that regex solution you mentioned will look like string getNumbers = Regex.Replace(ut.newTag, @"\D", ""));
Are you not lazy anymore? ;) Or still lazy but covertly.
@Silvermind ah, that would take so many efforts to explain.. :)
3

There's a ctor of String taking a char[] as parameter, so

var getNumbers = new String((from t in ut.newTag
                                where char.IsDigit(t)
                                select t).ToArray());
tech.PartialTag = Convert.ToInt32(getNumbers);

Difference with Sergey's answer :

if your input is 1A2 for example, Sergey's solution won't accept the input.

But my solution (based on yours) will take 12.

So, it depends on what you need (I think Sergey's one is clearer, it just rejects non integers inputs).

2 Comments

You can simplify string creation a little with new String(ut.newTag.Where(Char.IsDigit).ToArray()) :)
Yup, I know the fluent syntax, was just trying to be as closed as OP's try ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.