Cast IEnumerable<string> to IEnumerable<int> in C#

Mar*_*ego -3 .net c# visual-studio

I have:

IEnumerable<string> c = codigo_incidencia.Split('#');
Run Code Online (Sandbox Code Playgroud)

I need to cast "c" to be an IEnumerable<int>. I don´t know how to do this cast in C#.

Can someone help me?

Gil*_*een 6

最短的方法是.Select同样使用 linq :

var c = codigo_incidencia.Split('#').Select(int.Parse);
Run Code Online (Sandbox Code Playgroud)

如果您不确定这些部分是有效的整数,那么您需要使用TryParseas in: Select parsed int, if string was parseable to int。如果使用 C# 7.0,您可以查看这个问题的答案

var result = codigo_incidencia.Split('#')
                 .Select(s => new { Success = int.TryParse(s, out var value), value })
                 .Where(pair => pair.Success)
                 .Select(pair => pair.value);
Run Code Online (Sandbox Code Playgroud)


Adr*_*ian 5

使用 LINQ:

IEnumerable<int> c = codigo_incidencia.Split('#').Select(x => int.Parse(x));
Run Code Online (Sandbox Code Playgroud)