0

I'm trying to take objects out of an object list to an int list. If the object list's value contains a string than I want to convert it to an int. the error that I'm getting is "cannot convert from 'object' to 'System.ReadOnlySpan'. I've tried looking up examples and information about lists made of objects but couldn't find anything.

I'm also at a loss as to what to do with the 'else' part of the code.

public class ListFilterer
{
   public static IEnumerable(int) GetIntegersFromList(List(object) listOfItems)
   {

      List<int> Integers = new List<int>();

      foreach (var value in listOfItems)
      {
        int number = 0;

        bool success = Int32.TryParse(value, out number);

        if (success)
        {
          Integers.Add(number);
        }
        else
        {
          Integers.Add(number);
        }
      }
      return Integers;

   }
}
2
  • don't use parse it will give you error, get type of object if its int then parse it otherwise ignore it Commented Mar 5, 2020 at 6:36
  • so what do you suggest I use instead then? Commented Mar 5, 2020 at 6:37

4 Answers 4

1

It'll probably work out if you TryParse value.ToString() instead, if you're looking for anything that might look like an int and can be converted to an int. If you only want things that actually are ints, something like if(value is int number) should work if your c# version is recent. If it's older you may have to if(value is int) and then cast the value inside the if

Your code can be simplified to:

foreach(...){

  int.TryParse(value.ToString(), out var n);
  integers.Add(n);

}

Or

foreach(...){

  if(value is int)
    integers.Add((int)value);
  else 
    integers.Add(0);
}
Sign up to request clarification or add additional context in comments.

1 Comment

No probs. I added a bit more advice too
1

You could simply use:

var ints = listOfItems
  .Select(o => { int.TryParse(o.ToString(), out int num); return num;} )
  .ToList();

This will work as you wish, as if conversion fails num is 0 by default.

Comments

0

If Try Parse fails number is automatically 0 so you can directly write this

 Int32.TryParse(value, out int number)
 Integers.Add(number);

2 Comments

yep! thank you this and the comment above in combination made the code work! thank you!
value is object, not string.
0

Maybe you can find the better way

var intList = objs.ConvertAll(delegate (object obj) { return (int)obj; });

1 Comment

where objs is the list of objects

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.