在 C# 中将 List<string> 转换为 List<int>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19740383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:47:30  来源:igfitidea点击:

Convert List<string> to List<int> in C#

c#

提问by user2939293

I want to convert a List<string>to a List<int>.

我想将 a 转换List<string>为 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]));  
    }
)

采纳答案by Peter van der Heijden

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

您可以使用而不是使用 LINQ List<T>.ConvertAll<TOutput>(...)

List<int> intList = stringList.ConvertAll(int.Parse);

回答by Peter Kiss

With Linq:

与林克:

var intList = stringList.Select(x => int.Parse(x)).ToList();

回答by PMF

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:

如果你不想使用 Linq(我总是觉得很难理解),你的代码看起来是正确的,但当然你需要返回一些东西:

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.

请注意,如果字符串列表包含不可解析为 int 的内容,这将引发异常。

Edit:Better yet, use a foreach loop:

编辑:更好的是,使用 foreach 循环:

List<int> Convert(List<string> stringList)
{
    List<int> intList = new List<int>();  

    foreach(String s in stringList) 
    {  
        intList.Add(int.Parse(s));  
    }
    return intList;
}

回答by Jurgen Camilleri

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:

您的方法运行良好,因此我假设您是仍在学习该语言语法的初级开发人员。我暂时不会为您提供高级 LINQ 解决方案,但会帮助您使用当前代码实现您想要的。您当前没有返回您正在创建的列表,因此更改方法签名:

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 TryParseinstead of Parse, be careful however since this method works slightly differently and makes use of outparameters. You can learn more about it here.

注意:如果您不希望您的代码抛出异常,我是否建议使用TryParse而不是Parse,但是要小心,因为此方法的工作方式略有不同并且使用了out参数。您可以在此处了解更多信息。

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.

如果您对 LINQ 感兴趣,@Peter Kiss 的解决方案是最好的。他将 LINQ 与方法语法一起使用,但也有类似 SQL 的语法,您可能会或可能不会发现它们更容易掌握。可以在此处找到对 LINQ 的良好介绍。

回答by Marco

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.

我建议使用TryParse(),以防某些值无法转换为int. 为此,我创建了一个扩展方法。下面是我的演示 LinqPad 代码。

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.

在这种情况下,只有数字 int 值被解析,其余的被优雅地忽略。如果需要,您可以内置一些错误处理/通知。

/EditBased on Peter Kiss'suggestion here is a more generic approach based on the IEnumerable interface.

/Edit基于Peter Kiss 的建议,这里是一种基于 IEnumerable 接口的更通用的方法。

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.

有了这个,你只需要在调用AsEnumerable()之前调用ConvertToInt()结果当然是类型IEnumerable<Int32>,从这里开始,你可以通过使用.ToList()或数组或任何你需要的东西轻松地将它转换为列表。

回答by tariq

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:

如果您的 stringList 有一个无法解析的字符串,那么您可以使用默认错误/无效值说 -1 来屏蔽它,而不是遇到如下异常:

        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

// 现在你可以删除所有的 -1

        yourIntegerList = yourIntegerList.Where(a => a != -1).ToList();

回答by user2939293

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!

谢谢大家。在这里能得到多少帮助真是太棒了!我最终通过将字符串列表转换为数组,然后将数组转换为 int 来解决问题。也许不是最聪明的解决方案,但我的代码现在可以工作了。我稍后会尝试您的建议,看看我是否仍然可以使用 list 而不是 Array。谢谢大家!

回答by D Mishra

Use the following code:

使用以下代码:

int x = 0;

var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();