user2939293
user2939293

Reputation: 813

Convert List<string> to List<int> in C#

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

Upvotes: 24

Views: 57740

Answers (8)

heijp06
heijp06

Reputation: 11808

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

List<int> intList = stringList.ConvertAll(int.Parse);

Upvotes: 48

D Mishra
D Mishra

Reputation: 1578

Use the following code:

int x = 0;

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

Upvotes: 3

user2939293
user2939293

Reputation: 813

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!

Upvotes: 1

Marco
Marco

Reputation: 23945

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.

Upvotes: 15

tariq
tariq

Reputation: 2258

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();

Upvotes: -1

PMF
PMF

Reputation: 17298

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

Upvotes: 1

Jurgen Camilleri
Jurgen Camilleri

Reputation: 3589

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.

Upvotes: 0

Peter Kiss
Peter Kiss

Reputation: 9329

With Linq:

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

Upvotes: 5

Related Questions