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]));  
    }
)
Mike G
  • 4,232
  • 9
  • 40
  • 66
user2939293
  • 793
  • 5
  • 16
  • 41

8 Answers8

48

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

List<int> intList = stringList.ConvertAll(int.Parse);
heijp06
  • 11,558
  • 1
  • 40
  • 60
  • I tried this and got System.FormatException: 'Input string was not in a correct format.' – Goblinkiller Mar 14 '20 at 04:37
  • 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](https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=netframework-4.8#System_Int32_Parse_System_String_System_IFormatProvider_). – heijp06 Mar 14 '20 at 08:31
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.

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
  • he's a starter why are you confusing him by using extension methods , linq and all... – Vishal Sharma Nov 02 '13 at 09:30
  • 1
    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 – Marco Nov 02 '13 at 09:49
  • in that case intro to contravariance will also be helpfull to all .. http://msdn.microsoft.com/en-us/library/vstudio/ee207183.aspx – Vishal Sharma Nov 02 '13 at 09:51
  • @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. – tariq Nov 02 '13 at 10:10
  • I like this solution but as an extension method you should use a more generic signature: IEnumerable as input and IEnumerable as return type. – Peter Kiss Nov 02 '13 at 10:27
  • Very good point, I took the freedom to edit it into my post as an alternative approach – Marco Nov 02 '13 at 10:44
  • add a check if the parameter "source" is null to return new List(); – CDrosos Sep 24 '20 at 11:56
5

With Linq:

var intList = stringList.Select(x => int.Parse(x)).ToList();
Peter Kiss
  • 9,309
  • 2
  • 23
  • 38
  • 3
    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). ...`. – Jeppe Stig Nielsen Nov 02 '13 at 09:26
  • @Peter Kiss , This may throw common exception of 'input string not in correct format'.. – tariq Nov 02 '13 at 10:15
  • 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? – Peter Kiss Nov 02 '13 at 10:18
3

Use the following code:

int x = 0;

var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();
Jose R
  • 738
  • 2
  • 10
  • 26
D Mishra
  • 1,518
  • 1
  • 13
  • 17
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;
}
PMF
  • 14,535
  • 3
  • 23
  • 49
  • This is fine, but of course in this case it is natural to use `foreach` instead of `for`. Or Linq, as you write. – Jeppe Stig Nielsen Nov 02 '13 at 09:29
  • If using a new List 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 will only have an empty array inside). – Peter Kiss Nov 02 '13 at 10:21
  • Thank you, I will use foreach instead – user2939293 Nov 02 '13 at 11:12
  • I find Linq much harder, and therefor prefer to use something else. – user2939293 Nov 02 '13 at 11:14
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!

user2939293
  • 793
  • 5
  • 16
  • 41
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.

Jurgen Camilleri
  • 3,559
  • 20
  • 45
  • 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 integers = this.Convert(strings); but it won't work. But thank you for your help – user2939293 Nov 02 '13 at 11:17
-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();
tariq
  • 2,193
  • 15
  • 26