24

I want to convert a List<string> to a List<int>.

Here is my code:

void Convert(List<string> stringList)
{
    List<int> intList = new List<int>();  
    for (int i = 0; i < stringList.Count; i++) 
    {  
        intList.Add(int.Parse(stringList[i]));  
    }
)
6
  • See stackoverflow.com/a/199484/896341 as well. Commented Nov 2, 2013 at 9:10
  • You should keep the intList somehow. It is natural to change void into intList and return intList;. Commented Nov 2, 2013 at 9:24
  • @user2939293 are you a beginner in csharp ? Commented Nov 2, 2013 at 9:43
  • @user2939293 , you have a lot of answers below everyone tried well. You should accept one that meets your requirement. Commented Nov 2, 2013 at 10:46
  • 1
    possible duplicate of How to convert List<string> to List<int>? Commented Apr 9, 2014 at 15:25

8 Answers 8

48

Instead of using LINQ you can use List<T>.ConvertAll<TOutput>(...)

List<int> intList = stringList.ConvertAll(int.Parse);
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and got System.FormatException: 'Input string was not in a correct format.'
In that case at least one of the strings in the list can not be converted to int. It might be a bogus value like "one" or string.Empty. It might be that the current system culture cannot be used to parse the string in that case you should pass a culture argument.
15

I would suggest using TryParse(), in case some of the values are not convertible into int. For this I have created an Extension Method. Below is my demo LinqPad code.

void Main()
{
    List<string> sourceList = new List<string> {"1", "2","3", "qwert","4", "5","6", "7","asdf", "9","100", "22"};
    //Dump is a LinqPad only method. Please ignore
    sourceList.ConvertToInt().Dump();
}

static public class HelperMethods
{
    static public List<int> ConvertToInt(this List<string> stringList)
    {
        int x = 0;
        var intList = stringList.Where(str => int.TryParse(str, out x))
                                .Select (str => x)
                                .ToList();
        return intList;

    }
}

In this case, only the numeric int values get parsed and the rest is gracefully ignored. You could built in some error handling / notification if you want to.

/Edit Based on Peter Kiss' suggestion here is a more generic approach based on the IEnumerable interface.

static public IEnumerable<int> ConvertToInt(this IEnumerable<string> source)
{
    int x = 0;
    var result = source.Where(str => int.TryParse(str, out x))
                        .Select (str => x);

    return result;      
}

With this you'd just have to call AsEnumerable() before calling ConvertToInt() The result is of course of type IEnumerable<Int32> and from here on, you can convert it easily into a List by using .ToList() or an array or whatever you need at that point.

7 Comments

he's a starter why are you confusing him by using extension methods , linq and all...
This answer is not only for the OP. Other users might search for an answer to this to someday and might want to reuse this many times. Therefor an extension method. I have deleted my initial comment, since I deemed it not appropriate. I think this covery it way better
in that case intro to contravariance will also be helpfull to all .. msdn.microsoft.com/en-us/library/vstudio/ee207183.aspx
@vishalsharma , The attempt must be the best answer, not the one based upon the OP's level which may or may not always be judged correctly.
I like this solution but as an extension method you should use a more generic signature: IEnumerable<string> as input and IEnumerable<int> as return type.
|
5

With Linq:

var intList = stringList.Select(x => int.Parse(x)).ToList();

3 Comments

Since the parameter list to the left of the lambda arrow => is identical to the parameterlist to the Parse method, this can be simplified to ... .Select(int.Parse). ....
@Peter Kiss , This may throw common exception of 'input string not in correct format'..
Ofcourse but maybe it's not a problem. Who knows? Maybe the problem would be to hide the exception with some fake return value like -1 after int.TryParse?
3

Use the following code:

int x = 0;

var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();

Comments

1

If you don't want to use Linq (which I always find hard to understand), your code looks right, but of course you need to return something:

List<int> Convert(List<string> stringList)
{
    List<int> intList = new List<int>();  

    for (int i = 0; i < stringList.Count; i++) 
    {  
        intList.Add(int.Parse(stringList[i]));  
    }
    return intList;
}

Be aware that this will throw an exception if the string list contains something that is not parseable as an int.

Edit: Better yet, use a foreach loop:

List<int> Convert(List<string> stringList)
{
    List<int> intList = new List<int>();  

    foreach(String s in stringList) 
    {  
        intList.Add(int.Parse(s));  
    }
    return intList;
}

4 Comments

This is fine, but of course in this case it is natural to use foreach instead of for. Or Linq, as you write.
If using a new List<T> instance to transform items from another collection which is already in memory then use it's Count() or Length to create the new List to specify it's size. With large collections can be a performance issue to always allocate more space for the items in the new list (new List<T> will only have an empty array inside).
Thank you, I will use foreach instead
I find Linq much harder, and therefor prefer to use something else.
1

Thank you all of you. It's fantastic how much help one can get here! I finally solved the problem by making the string list to an Array, and then converting the Array to int. Maybe not the brightest solution, but my code now works. I will try your suggestions later on to see if I can still use list instead of Array. Thank you all of you!

Comments

0

Your method works fine, so I am assuming you are a beginner developer who is still learning the syntax of the language. I will not give you the advanced LINQ solution just yet, but help you achieve what you want with your current code. You are currently not returning the list you are creating, so change the method signature from:

void Convert(List<string> stringList)

to:

List<int> Convert(List<string> stringList)

and at the very end just before the method ends add:

return intList;

Then in your code you can call it like so:

List<string> strings = new List<string> { "1", "2", "3" };
List<int> integers = this.Convert(strings);

Note: If you don't want your code to throw an exception, might I suggest using TryParse instead of Parse, be careful however since this method works slightly differently and makes use of out parameters. You can learn more about it here.

If you are interested in LINQ, @Peter Kiss's solution is as good as it gets. He is using LINQ with method syntax, but there's also SQL-like syntax which you may or may not find easier to grasp. A good introduction to LINQ can be found here.

1 Comment

Yes, I'm a begninner. I don't want to return the list. I want to do something with it later in the method, so therefor I'm using void. I have already tried List<int> integers = this.Convert(strings); but it won't work. But thank you for your help
-1

In case your stringList has a string that can't be parsed then you can mask that with a default error/invalid value of say -1, rather than encountering exception as below:

        List<string> stringList = new List<string>();
        stringList.AddRange(new string[] { "1", "2", "3", "4", "sdfsf", "7" }); // for illustration
        int temp;
        var yourIntegerList = stringList.Select(x => int.TryParse(x, out temp) ? int.Parse(x) : -1).ToList(); // -1 used here, can be any integer

// Now you may remove all -1's

        yourIntegerList = yourIntegerList.Where(a => a != -1).ToList();

3 Comments

Two parsing can lead some performance issue and -1 can hide errors in the input list and can make an invalid result if the input itself contains string with value "-1".
@PeterKiss , we all lack something don't we ? :D
Maybe there is no perfect solution for such simple problem? :D

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.