Convert List to List in C#

前端 未结 8 2317
长情又很酷
长情又很酷 2021-02-12 13:01

I want to convert a List to a List.

Here is my code:

void Convert(List stringList)
{         


        
8条回答
  •  不知归路
    2021-02-12 13:43

    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 Convert(List stringList)
    {
        List intList = new List();  
    
        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 Convert(List stringList)
    {
        List intList = new List();  
    
        foreach(String s in stringList) 
        {  
            intList.Add(int.Parse(s));  
        }
        return intList;
    }
    

提交回复
热议问题