在List< int>中转换字符串使用LINQ(更清洁的方式)

问题描述:

我有这个字符串:

string input = "1,2,3,4,s,6";

请注意s字符.

我只想使用LINQ在List<int>中转换此字符串.我最初以这种方式尝试过:

I just want to convert this string in a List<int> using LINQ. I initially tried in this way:

var myList = new List<int>();
input.Split(',').ToList().ForEach(n =>
    myList.Add(int.TryParse(n, out int num) ? num : -1)
);
lista.RemoveAll(e => e == -1);

但是我更希望没有任何-1而不是没有数字的字符.

But I prefer not have any -1 instead of a no-number characters.

所以现在我尝试一下:

var myList = new List<int>();
input.Split(',').ToList()
    .FindAll(n => int.TryParse(n, out int _))
    .ForEach(num => myList.Add(int.Parse(num)));

我更喜欢这样做,但是解析两次进行(第一次TryParse然后是Parse),实在令人遗憾.但是,据我了解,TryParse中的out变量是无用的(或没有?).

I prefer this, but is really a shame that the parsing happening two times (TryParse at first and then Parse). But, from what I understand, the out variable in TryParse is useless (or not?).

您是否有其他建议(使用LINQ)?

Have you others suggests (using LINQ)?

public class ParsesStringsToIntsWithLinq
{
    public IEnumerable<int> Parse(string input)
    {
        var i = 0;
        return (from segment in input.Split(',')
            where int.TryParse(segment, out i) 
            select i);
    }
}

[TestClass]
public class Tests
{
    [TestMethod]
    public void IgnoresNonIntegers()
    {
        var input = "1,2,3,4,s,6";
        var output = new ParsesStringsToIntsWithLinq().Parse(input);
        Assert.IsTrue(output.SequenceEqual(new []{1,2,3,4,6}));
    }
}

它不返回List<int>,但是我必须在某处画线.您可以从中列出一个清单.

It doesn't return a List<int> but I have to draw the line somewhere. You can make a list out of it.