Convert List to List in C#

前端 未结 8 2288
长情又很酷
长情又很酷 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:56

    With Linq:

    var intList = stringList.Select(x => int.Parse(x)).ToList();
    
    0 讨论(0)
  • 2021-02-12 14:01

    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.

    0 讨论(0)
提交回复
热议问题