Convert List to List in C#

前端 未结 8 2353
长情又很酷
长情又很酷 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 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 sourceList = new List {"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 ConvertToInt(this List 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 ConvertToInt(this IEnumerable 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 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.

提交回复
热议问题