Convert List to List in C#

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

I want to convert a List to a List.

Here is my code:

void Convert(List stringList)
{         


        
8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 13:50

    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 stringList = new List();
            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();
    

提交回复
热议问题